Flutter共享首选项已在其他类别中访问

时间:2019-12-09 15:50:17

标签: flutter sharedpreferences

在下面的类中,我创建了一个String的ListView,它们使用共享的首选项进行存储。现在,我需要在另一个类中访问List<String> categoryList的内容。我不知道在何处实现get函数以使其他类可以访问此List。

  

一个想法是为列表创建一个类(但我不想弄乱所有内容)

这是我的带有列表视图的班级

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

class Categories extends StatefulWidget {
  @override
  _CategoriesState createState() => _CategoriesState();
}

class _CategoriesState extends State<Categories> {
  List<String> categoryList = List<String>();
  TextEditingController _textFieldController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    _update();
    return Scaffold(
      appBar: AppBar(
        title: Text("Categories"),
      ),
      body: SafeArea(
        child: Container(
          color: Colors.white,
          child: getCategoriesListView(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            _displayDialog(context);
          });
        },
      ),
    );
  }

  ListView getCategoriesListView() {
    return ListView.builder(
        itemCount: categoryList.length,
        itemBuilder: (context, int position) {
          return Card(
            color: Colors.white,
            elevation: 2.0,
            child: ListTile(
              title: Text(categoryList[position]),
              trailing: GestureDetector(
                child: Icon(
                  Icons.delete,
                  color: Colors.grey,
                ),
                onTap: () {
                  setState(() {
                    _delete(context, categoryList[position]);
                  });
                },
              ),
            ),
          );
        });
  }

  void _add(BuildContext context, String category) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    categoryList.add(category);
    prefs.setStringList('Categories', categoryList);
  }

  void _delete(BuildContext context, String category) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    categoryList.remove(category);
    prefs.setStringList('Categories', categoryList);
  }

  void _update() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      categoryList = prefs.getStringList('Categories');
    });
  }

  void showSnackBar(BuildContext context, String message) async {
    final snackBar = SnackBar(content: Text(message));
    Scaffold.of(context).showSnackBar((snackBar));
  }

  _displayDialog(BuildContext context) async {
    _textFieldController.clear();
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Add new category'),
            content: TextField(
              controller: _textFieldController,
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('ADD'),
                onPressed: () {
                  setState(() {
                    String name = _textFieldController.text;
                    _add(context, name);
                    Navigator.of(context).pop();
                  });
                },
              ),
              FlatButton(
                child: Text('CANCEL'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }
}

第二堂课

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

class MonthlyOverview extends StatefulWidget {
  @override
  _MonthlyOverviewState createState() => _MonthlyOverviewState();
}

class _MonthlyOverviewState extends State<MonthlyOverview> {
  List<String> _categories = new List<String>();
  @override
  Widget build(BuildContext context) {
    _getCategory().then((value) {
      _categories = value;
    });
    print(_categories);
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        color: Colors.white,
      ),
    );
  }

  _getCategory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> categoryList = prefs.getStringList('Categories');
    return categoryList;
  }
}

控制台输出 I/flutter (13417): []

1 个答案:

答案 0 :(得分:1)

@Frederik,您是否尝试过在第二个类中实现get函数并访问列表?在您的第二堂课中可能是这样的,

_getCategory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> categoryList = prefs.getStringList('Categories');
    return categoryList;
  }

呼叫(取决于您在哪里呼叫,但这应该可以给您一个想法):

List<String> _categories = new List<String>();
_getCategory().then((value) {
 _categories = value;
});
//Your _categories has the value now , use it here.

完整代码:

void main() {
  runApp(MaterialApp(
      home: new MyApp(),
      routes: <String, WidgetBuilder>{
        "/monthlyOverview" : (BuildContext context)=> new MonthlyOverview(),
        //add more routes here
      }
  ));
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Center(
                    child: FlatButton(
                      child: Text('Next', style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),),
                      onPressed: () async {
                        List<String> categoryList = ['Item 1', 'Item 2', 'Item 3'];
                        SharedPreferences prefs = await SharedPreferences.getInstance();
                        prefs.setStringList('Categories', categoryList);
                        Navigator.of(context).pushNamed("/monthlyOverview");
                      },
                    )
                  )
                  ),
    );
  }

}

class MonthlyOverview extends StatefulWidget {
  @override
  _MonthlyOverviewState createState() => _MonthlyOverviewState();
}

class _MonthlyOverviewState extends State<MonthlyOverview> {
  List<String> _categories = new List<String>();

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

    _getCategory().then((value) {
      _categories = value;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Center(
            child: Container(
              color: Colors.white,
              child: _categories.length > 0 ? Text(_categories[0] + '\n' + _categories[1] + '\n' + _categories[2], style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),) : Text(''),
            )
        ),
    );
  }

  _getCategory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> categoryList = prefs.getStringList('Categories');
    return categoryList;
  }
}

demo

希望这会有所帮助。