Flutter中的共享首选项无法保存和读取列表

时间:2019-04-06 02:27:27

标签: dart flutter

我正在使用一些共享的首选项来读取和保存列表,但是我得到的只是一个错误,如下所示:

    Launching lib/main.dart on iPhone 7 in debug mode...
    Xcode build done.                                            4.1s
    Tried calling: getString("t")
#0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1      ShareUtils.get
package:todolist2019/ShareUtils.dart:22
<asynchronous suspension>
#2      HomeScreenState.getTaskTitle
package:todolist2019/home.dart:38
#3      _AsyncAwaitCompleter.start (dart:async/runtime/libasync_patch.dart:49:6)
#4      HomeScreenState.getTaskTitle
package:todolist2019/home.dart:35
#5      HomeScreenState.build.<anonymous closure>
package:todolist2019/home.dart:97
#6      SliverChildBuilderDelegate.build 
package:flutter/…/widgets/sliver.dart:398

这是我的主屏幕代码home.dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import './additem.dart';

import './ShareUtils.dart';
class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return HomeScreenState();
  }
}

Timer timer;

DateTime now = DateTime.now();
String formattedTime = DateFormat('kk:mm').format(now);
String formattedDate = DateFormat('EEE d MMM').format(now);



class HomeScreenState extends State<HomeScreen> {
  void changeTimeAndSetPref() {
    setState(() {
      DateTime now = DateTime.now();
      formattedTime = DateFormat('kk:mm').format(now);
      formattedDate = DateFormat('EEE d MMM').format(now);


    });
  }

 Future getTaskTitle(index) async {
  shareUtils = new ShareUtils();
  shareUtils.Instance();
  await shareUtils.get("title"[index]);

}

  void initState() {
    super.initState();
    // Add listeners to this class
    timer = Timer.periodic(Duration(seconds: 1), (Timer t) => changeTimeAndSetPref());

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    return Scaffold(
      floatingActionButton: FloatingActionButton.extended(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => addItem()),
            );
          },
          icon: Icon(Icons.add),
          label: Text("Add Item"),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      body: Column(
        children: <Widget>[
          Center(
            //set the correct sizes
            child: Card(
              child: Column(
                children: <Widget>[
                  Text(
                    formattedTime,
                    style: TextStyle(
                      fontSize: 50.0,
                    ),
                  ),
                  Text(
                    formattedDate,
                    style: TextStyle(
                      fontSize: 35.0,
                    ),
                  ),
                  Text(
                    "You have  impending tasks",
                    style: TextStyle(
                      fontSize: 25.0,
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    var title = getTaskTitle(index).toString();
                    var detail = taskTitleList[index];
                     EdgeInsets.all(16.0);

                    return ListTile(
                      title: Text(
                        title,
                        style: TextStyle(fontSize: 20.0),
                      ),
                      subtitle: Text(
                        detail,
                        style: TextStyle(fontSize: 15.0),
                      ),
                      onTap: () {
                        final snackBar = SnackBar(
                          content: Text('Item Removed'),
                          duration: Duration(seconds: 1),
                        );
                        setState(() {
                          taskTextList.removeAt(index);
                          taskTitleList.removeAt(index);
                          Scaffold.of(context).showSnackBar(snackBar);
                        });
                      },
                    );
                  },
                  itemCount: taskTextList.length,
                ),
              )


        ],
      ),
    );
  }
}

这是我的additem.dart代码

import 'package:flutter/material.dart';
import './home.dart';
import './ShareUtils.dart';
class addItem extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return addItemState();
  }
}

ShareUtils shareUtils;
var TaskTextField;
var TaskDetailField;
var taskTextList = [];
var taskTitleList = [];
var TaskIsImportant = false;


class addItemState extends State<addItem> {

   @override
  Widget build(BuildContext context) {
    // TODO: implement build
  void saveTask (key, value) async {
    await shareUtils.set(key, value);
  }
    return Scaffold(
        floatingActionButton: FloatingActionButton.extended(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => HomeScreen()),
            );
            setState(()async {
              if (TaskIsImportant) {

                taskTextList.add("❗$TaskTextField");
                taskTitleList.add("$TaskDetailField");
                saveTask("title", taskTextList);
              } else {
                taskTextList.add("$TaskTextField");
                taskTitleList.add("$TaskDetailField");
                saveTask("title", taskTextList);
              }
            });
          },
          label: Text("Add Task"),
          icon: Icon(Icons.add),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        body: Flex(
          direction: Axis.vertical,
          children: <Widget>[
            Flexible(
              child: Container(
                child: Column(
                  children: <Widget>[
                    Card(
                      child: Column(
                        children: <Widget>[
                          Center(
                            child: Text(
                              "Welcome!",
                              style: TextStyle(fontSize: 50.0),
                            ),
                          ),
                          Center(
                            child: Text(
                              "Enter your task below",
                              style: TextStyle(fontSize: 25.0),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      child: TextField(
                        decoration: InputDecoration(
                            hintText: "Enter title of task to be added",
                            hintStyle: TextStyle(fontSize: 20.0)),
                        onChanged: (taskTextField) {
                          setState(() {
                            TaskTextField = taskTextField;
                            print(TaskTextField);
                          });
                        },
                      ),
                      margin: EdgeInsets.all(16.0),
                    ),
                    Container(
                      child: TextField(
                        decoration: InputDecoration(
                            hintText: "Enter detail of task to be added",
                            hintStyle: TextStyle(fontSize: 20.0)),
                        onChanged: (taskDetailField) {
                          setState(() {
                            TaskDetailField = taskDetailField;
                            print(TaskDetailField);
                          });
                        },
                      ),
                      margin: EdgeInsets.all(16.0),
                    ),
                    CheckboxListTile(
                      title: Text(
                        "Important",
                        style: TextStyle(fontSize: 25.0),
                      ),
                      activeColor: Colors.blue,
                      value: TaskIsImportant,
                      onChanged: (val) {
                        setState(() {
                          TaskIsImportant = !TaskIsImportant;
                          print(TaskIsImportant);
                        });
                      },
                    ),
                  ],
                ),
              ),
            )
          ],
        ));
  }

}

我希望有人可以帮助我解决此错误。我正在Flutter 1.2.1上运行。提前致谢! PS:我已经实现了Akio的代码,但仍然出现错误,但错误程度要小一些。我还添加了错误消息的前6行。

1 个答案:

答案 0 :(得分:1)

您可以在pubspec.yaml中添加“ shared_preferences:^ 0.4.0”。

然后得到包。 然后创建DartFile(例如:文件名是ShareUtils

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

class ShareUtils {
  static ShareUtils _instance;
  SharedPreferences ShareSave;
  factory ShareUtils() => _instance ?? new ShareUtils._();

  ShareUtils._();

  void Instatce() async{
  ShareSave = await SharedPreferences.getInstance();
}


  Future<bool> set(key, value) async{
   return ShareSave.setString(key, value);

  }

  Future<String> get(key) async{
   return ShareSave.getString(key);
  }
}

和main.dart

class MyApp extends StatelessWidget {
static ShareUtils shareUtils;

@override
Widget build(BuildContext context) {
  ThemeData mainTheme = new ThemeData(
    primaryColor : Color.fromRGBO(20, 42, 59, 1),
    buttonColor: Color.fromRGBO(0, 132, 255, 1),
    accentColor: Color.fromRGBO(31, 60, 83, 1)
  );
  shareUtils = new ShareUtils();
  shareUtils.Instatce();
  MaterialApp mainApp = new MaterialApp(
    title: "Your app name",
    theme: mainTheme,
    home: new SplashPage(),
    debugShowCheckedModeBanner: true,
    routes: <String, WidgetBuilder>{
      "HomePage": (BuildContext context) => new HomePage(),
    },
  );
  return mainApp;
}

}

您可以在任何地方使用它

在使用此功能之前,请在标题中添加import main.dart

获取:

  Future NextPage() async {
   MyApp.shareUtils.get("token").then((token) {
    print(token);
    if (token == null || token == "") {
      Navigator.of(context).popAndPushNamed("RegisterPage");
    } else {
      Navigator.of(context).popAndPushNamed("HomePage");
    }
  });
  }  

设置:

    void UserInfo(code, token) async{
      await MyApp.shareUtils.set("token", token);
      await MyApp.shareUtils.set("code", code);
      await Navigator.of(context).pushNamed("HomePage");
    }

希望对您有所帮助。谢谢

在您的情况下,MyApp.shareUtils.set(“ state”,statelist.join(“ @”))

并使用statelist = token.split(“ @”);