Persisting data in a flutter application

天涯浪子 提交于 2021-02-16 15:32:13

问题


I am building an app and in it, I have the names of people in a list from which I could add/delete, etc.. The problem is this list is not saved when I close the app, which is inconvenient.

I heard you can use shared Preferences to save simple objects like this, without complicating things like using SQLite and json.

So I'd like to know what's the suggested way to persist this data and load it etc.

Thanks in Advance and have a great day :)

Here is the code:

import 'package:flutter/material.dart';
import 'package:zakif_yomi3/NewPerson.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  final List<String> people = [];

  void _addNewPerson(String name) {
    setState(() {
      people.add(name);
    });
  }

  void _startAddNewPerson(BuildContext ctx) {
    showModalBottomSheet(
      context: ctx,
      builder: (_) {
        return GestureDetector(
          onTap: () {},
          child: NewPerson(_addNewPerson),
          behavior: HitTestBehavior.opaque,
        );
      },
    );
  }
void _deletePerson(int value  ) {

    setState(() {
      people.removeAt(value);
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          'People',
          style: TextStyle(fontSize: 30),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => _startAddNewPerson(context),
          )
        ],
      ),
      body: ListView.builder(
        itemCount: this.people.length,
        itemBuilder: (context, value) {
          return Card(
            color: Colors.amberAccent[200],
            elevation: 3,
            child: Container(
              child: ListTile(
                leading: Text(value.toString()),
                title: Text(
                  people[value],
                ),
                trailing: IconButton(
                  icon: Icon(Icons.delete),
                  onPressed: () {
                    _deletePerson(value);
                  },
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

And the NewPerson object:

import 'package:flutter/material.dart';


class NewPerson extends StatefulWidget {
  final Function addTx;

  NewPerson(this.addTx);

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

class _NewPersonState extends State<NewPerson> {
  final _nameController = TextEditingController();



  void _submitData() {

    final name = _nameController.text;


    widget.addTx(
     name
    );

    Navigator.of(context).pop();
  }



  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 5,
      child: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Name'),
              controller: _nameController,
              onSubmitted: (_) => _submitData(),

            ),


            RaisedButton(
              child: Text('Add Person'),
              color: Theme.of(context).primaryColor,
              textColor: Theme.of(context).textTheme.button.color,
              onPressed: _submitData,
            ),
          ],
        ),
      ),
    );
  }
}

回答1:


You could use this functions to persist and load data from shared preferences.

Get SharedPreferences from here.

To persist data to SharedPreferences, called after adding or deleting a new element to the list.

_persistData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    await preferences.setStringList("persons", _people);
  }

To load data from SharedPreferences, usually called in initState.

_loadData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
      _people = preferences.getStringList("persons");
    });
  }


来源:https://stackoverflow.com/questions/59499200/persisting-data-in-a-flutter-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!