【问题标题】:How to save a boolean state in main.dart so it is retained throughout app如何在 main.dart 中保存布尔状态,以便在整个应用程序中保留它
【发布时间】:2022-08-04 03:31:26
【问题描述】:

关闭或重新加载应用程序后,我在仪表板屏幕中保留布尔值状态时遇到了挑战。

在仪表板屏幕上,有一个 ListTile,我可以通过点击该卡片将卡片标记为已验证。一旦卡片被点击,我将 bool 验证状态从 false 设置为 true,只要我没有关闭或重新加载应用程序,它就可以正常工作。一旦应用程序关闭或重新加载,布尔状态将设置回 false。

如何在main.dart 中初始化布尔状态,以便在从仪表板屏幕设置后始终保留已验证状态并且可以在应用程序内的任何地方(更多屏幕)使用

这是代码:

仪表板屏幕

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

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

class _DashboardState extends State<Dashboard> {
  
  bool _verified = false;


  //Retrieving card info from database
  bool isFetching = false;
  late String cardInfo = retrieveData;  //url to php script for retrieving from database

  List cardData = [];

  getCardData() async {
    setState(() => isFetching = true);
    
    var response = await http.get(Uri.parse(cardInfo));
    if (response.statusCode == 200) {
      setState(() {
        cardData = json.decode(response.body);
      });
    }
    setState(() => isFetching = false);

    return cardData;
  }

  
  @override
  void initState() {
    super.initState();

   getCardData();

    _verified;
  }


 @override
  Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(
title: Text(\'Approve Card\'),
centerTitle: true,
),

body: Container(
                  child: Card(
                    child: ListView.builder(
                        physics: const ClampingScrollPhysics(),
                        shrinkWrap: true,
                        primary: false,
                        itemCount: cardData.length, //coming from mysql database
                        itemBuilder: (context, index) {
                          return ListTile(
                            leading: Container(
                              padding: const EdgeInsets.only(left: 15.0),
                              alignment: Alignment.center,
                              height: 50,
                              width: 50,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(50.0),
                                image: DecorationImage(
                                  image: NetworkImage(
                                      \'http://url/uploads/${cardData[index][\'logo\']}\'),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            title: Text(
                              cardData[index][\'name\'],
                              style: TextStyle(
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            subtitle: Text(
                              cardData[index][\'email\'],
                            ),
                            trailing: Bounce(
                              duration: const Duration(milliseconds: 100),
                              onPressed: () { //onPressed set verified state to true
                //After app is reloaded, it is set back to false
                                setState(() {
                                  col = iconTip;
                                  _verified = true;
                                });

                                var url = Uri.parse(verifiedCards), //http url to php script
                                    response = http.post(url, body: {
                                      \"card\": cardData[index][\'card\'],
                                    });

                                getCardData();

                              },
                              child: Container(
                                padding: const EdgeInsets.all(15.0),
                                color: col,
                                child: Icon(Icons.check_sharp),
                              ),
                            ),
                          );
                        }),
                  ),
                ),
);

}

}

}

Main.dart 屏幕

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: My Flutter App,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSwatch(
          primarySwatch: Colors.green,
          backgroundColor: white,
        ),
      ),
      initialRoute: \'/\',
      routes: {
        \'/\': (context) => const SplashScreen(),
        
        \'/dashboard\': (context) => const Dashboard(),
      },
    );
  }
}
  • 如果您想保存整个应用程序的状态,那么您需要使用“提供程序包”。请检查文档pub.dev/packages/provider
  • 是的,我想保存整个应用程序

标签: flutter dart


【解决方案1】:

使用 shared_preferences 包保存需要在应用重新加载之间保留的数据。

https://pub.dev/packages/shared_preferences

// Save value
await prefs.setBool('verified', true);

// Read value 
final bool? verified= prefs.getBool('verified');

【讨论】:

    【解决方案2】:

    当您想更改整个应用程序的应用程序状态时,您可以使用Provider Package

    1. 首先创建模型类
      class MyChangeNotifier extends ChangeNotifier{
        bool _verified;
      
        void setVarified(bool verified){
         _verified = verified;
         notifyListeners();
        }
        bool get verified => _verified;
      }
      
      1. 使用main.dart 文件附加通知程序。
      runApp(MultiProvider(
        providers: [
          Provider<MyChangeNotifier>(create: (_) => MyChangeNotifier()),
        ],
        child: MyApp(),
      ));
      
      1. 在您的应用程序中使用状态
      // For change State from widgets
      ElevatedButton(onPressed: (){
            context.read<MyChangeNotifier>().setVarified([true / false]);
          }, child: Text('Event Setter'));
      
      // Access State for widget
      bool check = context.read<MyChangeNotifier>().verified;
      

      另外,您可以查看Flutter State Management in Hindi 视频教程以获得更多帮助。

    【讨论】:

      【解决方案3】:

      Shared Preference 的完整示例:

      写入布尔值:

      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setBool('isfirstRun', false);
      

      读取布尔值:

      SharedPreferences prefs = await SharedPreferences.getInstance();
      bool myboolean = prefs.getBool(key) ?? true; // Or false depending of what you want for default value. This is required for Null safety
      

      并且不要忘记导入共享首选项包:

      import 'package:shared_preferences/shared_preferences.dart'; 
      

      【讨论】:

        【解决方案4】:

        谢谢大家的回答,我很感激。我用我曾经使用过的共享偏好来解决这个问题。我在想有一种方法可以在不使用共享首选项的情况下做到这一点,但由于它可以完成工作并且不太复杂,所以我决定使用它

        【讨论】:

          猜你喜欢
          • 2012-01-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-09
          • 1970-01-01
          • 2015-12-31
          • 1970-01-01
          • 2010-12-21
          相关资源
          最近更新 更多