0

I'm new to programming, and flutter. and trying to make a simple expense app model.

whenever i press the floating button a new text field is created but i want to keep the number of text fields made and the value that added to the text field after restarting the app.. only using shared preference.

this is my code,

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

void main() {
  runApp(
    MaterialApp(
      home: Test(),
    ),
  );
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  final _formKey = GlobalKey<FormState>();

  List<TextEditingController> textFieldControllers = [];
  int numberOfTextFields = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
      backgroundColor: Color.fromARGB(244, 238, 235, 249),
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(top: 250),
        child: FloatingActionButton(
          backgroundColor: Colors.green,
          child: Icon(
            Icons.add,
          ),
          onPressed: () {
            addNewTextField();
          },
        ),
      ),
      body: Stack(
        children: [
          Form(
            key: _formKey,
            child: ListView.builder(
              itemCount: numberOfTextFields.bitLength,
              itemBuilder: (BuildContext context, int index) {
                return TextFormField(
                  decoration: InputDecoration(
                    label: Text(' ${index + 1}/01/2023'),
                    prefixText: 'Day ${index + 1} - ',
                  ),
                  keyboardType: TextInputType.number,
                  controller: textFieldControllers[index],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  void addNewTextField() {
    textFieldControllers.add(TextEditingController());
    if (numberOfTextFields < 30) {
      numberOfTextFields++;
    }

    setState(() {});
  }

  @override
  void dispose() {
    textFieldControllers
        .forEach((textFieldController) => textFieldController.dispose());
    super.dispose();
  }
}

I tried using shared preference by myself but it's not working. (I want to use only shared preference to keep the text field)

Nikhil K
  • 21
  • 2

0 Answers0