Home > Software engineering >  How to use shared preference in flutter with dynamic forms
How to use shared preference in flutter with dynamic forms

Time:12-31

in my app i am generating forms dynamically, i want to store every form data to be stored locally so that i can use it in my app. i also want the form textfield to be filled autometically with the previous data the user has entered with initstate but i am unable to implemet it.

i am expecting to store each form data locally, to use that later. secondly i want the form fields to be filled when the app is opened with the data that user has entered previously. enter image description here

CodePudding user response:

It would be more practical for you to generate a JSON from this form. This way it will save and retrieve only a single field. When retrieving the JSON you get a MAP there it's easy to find the field and restore its value. But, use it in moderation, pay attention to the limitations of the package

CodePudding user response:

You can save the data simply by storing it in the shared preference key-value store. When you can save data like this : -

pref.setString("userName", userName.text); 

In the above code, first parameter(userName) is the name of the shared preference variable and the second parameter(userName.text) is the value.

Data can be fetched in this way : -

userName.text = pref.getString("userName") ?? ''; // Pass the name of the variable

Latest shared_preferences version has some bugs in it hence use the stable version, shared_preferences: 2.0.0

Full Code : -

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

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared Preference',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: const SharedPreference(),
    );
  }
}

class SharedPreference extends StatefulWidget {
  const SharedPreference({Key? key}) : super(key: key);
  @override
  _SharedPreferenceState createState() => _SharedPreferenceState();
}

class _SharedPreferenceState extends State<SharedPreference> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Shared Preference"),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: ElevatedButton(
            child: const Text("User's Data"),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const UserForm()),
              );
            },
          ),
        ));
  }
}

class UserForm extends StatefulWidget {
  const UserForm({Key? key}) : super(key: key);
  @override
  _UserFormState createState() => _UserFormState();
}

class _UserFormState extends State<UserForm> {
  TextEditingController userName = TextEditingController();
  TextEditingController userAge = TextEditingController();

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

  loadData() {
    SharedPreferences.getInstance().then((pref) {
      setState(() {
        userName.text = pref.getString("userName") ?? '';
        userAge.text = pref.getString("userAge") ?? '';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Shared Preference"),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.only(left: 20, right: 20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TextField(
                  controller: userName,
                  decoration: const InputDecoration(hintText: 'Username'),
                ),
                const SizedBox(
                  height: 30,
                ),
                TextField(
                  controller: userAge,
                  decoration: const InputDecoration(hintText: 'Age'),
                ),
                const SizedBox(
                  height: 30,
                ),
                ElevatedButton(
                  child: const Text("Save"),
                  onPressed: () async {
                    Navigator.pop(context);
                    final pref = await SharedPreferences.getInstance();
                    pref.setString("userName", userName.text);
                    pref.setString("userAge", userAge.text);
                  },
                ),
              ],
            ),
          ),
        ));
  }
}
  • Related