Home > Blockchain >  How to save a boolean state in main.dart so it is retained throughout app
How to save a boolean state in main.dart so it is retained throughout app

Time:07-29

I have a challenge in retaining a boolean value state in my dashboard screen after I close or reload app.

On the dashboard screen, there is a ListTile where I can mark a card as verified by tapping on that card. Once the card is tapped, I set the bool verified state from false to true which works fine as long as I haven't closed or reloaded the app. Once the app is closed or reloaded, the boolean state is set back to false.

How can I initialize the boolean state in main.dart so that the verified status is always retained once it is set from the dashboard screen and can be used anywhere (more screens) within the app

here is the code:

Dashboard screen

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 screen

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(),
      },
    );
  }
}

CodePudding user response:

Use the shared_preferences package to save data that needs to persist between app reloads.

https://pub.dev/packages/shared_preferences

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

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

CodePudding user response:

When you want to change your application state entire application then you can use Provider Package.

  1. First create Model Class
class MyChangeNotifier extends ChangeNotifier{
  bool _verified;

  void setVarified(bool verified){
   _verified = verified;
   notifyListeners();
  }
  bool get verified => _verified;
}
  1. Attach Notifier with main.dart file.
runApp(MultiProvider(
  providers: [
    Provider<MyChangeNotifier>(create: (_) => MyChangeNotifier()),
  ],
  child: MyApp(),
));
  1. Use State in your application
// 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;

Also, you can check Flutter State Management in Hindi video tutorial for more help.

CodePudding user response:

A complete example with Shared Preference :

Writing boolean value:

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

Reading boolean value:

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

And don't forget to import share preference package:

import 'package:shared_preferences/shared_preferences.dart'; 
  • Related