flutter 当我按下冷重新加载时,DateTime的变量日期未保存

ohtdti5x  于 2023-01-02  发布在  Flutter
关注(0)|答案(1)|浏览(177)

我使用Share_Prefereces库,所以我想保存添加项目的日期。我尝试了许多方法,但
我总是得到错误:E/扑动(2786):[错误:flutter/运行时/dart_vm_initializer. cc(41)]未处理的异常:类型"Null"不是类型"DateTime"的子类型
第二个误差是:未处理的异常:将对象转换为可编码对象失败:"购物"示例
所以请帮帮我
日期文件的编码为:

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Shopping {
  String item;
  int price;
  DateTime date;
  Shopping({required this.item, required this.price, required this.date});
  Map<String, dynamic> toJson() {
    return {
      'item': item,
      'price': price,
      'date': date,
    };
  }

}

class ItemData extends ChangeNotifier {
  List<Shopping> listOfItem = [];
  void addItem(Shopping shopping) {
    listOfItem.add(shopping);
    notifyListeners();
  }

  void editItem(Shopping shopping, int itemIndex) {
    listOfItem[itemIndex] = shopping;
    notifyListeners();
  }

  void deleteItem(int itemIndex) {
    listOfItem.removeAt(itemIndex);
    notifyListeners();
  }

  saveData() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    List<String> tempList = [];
    for (int i = 0; i < listOfItem.length; i++) {
      tempList.add(jsonEncode(listOfItem[i]));
    }
    pref.remove("itemList");
    pref.setStringList("itemList", tempList);
  }

  loadData() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    if (pref.getStringList('itemList') != null) {
      List<String> tempList = pref.getStringList('itemList')!;
      for (int i = 0; i < tempList.length; i++) {
        Map<String, dynamic> temp = jsonDecode(tempList[i]);
        addItem(
          Shopping(
            item: temp['item'],
            price: temp['price'],
            date: temp['date'],
          ),
        );
      }
    }
  }
}

增加项目、价格、日期的代码为:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:goods_and_price/shopping_data.dart';
import 'package:provider/provider.dart';

class AddItem extends StatelessWidget {
  AddItem({Key? key}) : super(key: key);

  TextEditingController userInputItem = TextEditingController();

  TextEditingController userInputPrice = TextEditingController();

  @override
  Widget build(BuildContext context) {
    var provider = Provider.of<ItemData>(context, listen: true);
    DateTime date = DateTime.now();
    return Scaffold(
      appBar: AppBar(
        title: const Text('Add Item'),
        centerTitle: true,
        backgroundColor: const Color(0xFF00899C),
      ),
      body: ListView(
        physics: const BouncingScrollPhysics(),
        children: [
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextField(
              controller: userInputItem,
              decoration: InputDecoration(
                  hintText: 'Item',
                  labelText: 'Item',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  prefixIcon: const Icon(
                    Icons.shopping_cart,
                    color: Color(0xFF00899C),
                  )),
              maxLines: null,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextField(
              controller: userInputPrice,
              decoration: InputDecoration(
                  hintText: 'Price',
                  labelText: 'Price',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  prefixIcon: const Icon(
                    Icons.attach_money,
                    color: Color(0xFF00899C),
                  )),
              maxLines: null,
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          CupertinoButton(
            padding: const EdgeInsets.all(0),
            pressedOpacity: 0.5,
            child: Container(
              height: 50,
              width: 120,
              decoration: BoxDecoration(
                  color: const Color(0xFF00899C),
                  borderRadius: BorderRadius.circular(10)),
              child: const Center(
                child: Text(
                  'Add Item',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            onPressed: () async {
              Shopping newItem = Shopping(
                item: userInputItem.text,
                price: int.parse(userInputPrice.text),
               date: date,
              );
              provider.addItem(newItem);
              provider.saveData();
              Navigator.pop(context);
            },
          ),
        ],
      ),
    );
  }
}
yr9zkbsy

yr9zkbsy1#

我不推荐使用DateTime,因为在不同的语言中使用它需要一定的工作量,我发现使用String更容易。
我不能在我的机器上模拟错误,但我做了一个例子,我希望它能有所帮助。
要创建类我喜欢使用此网站https://javiercbk.github.io/json_to_dart/

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:zoociadoleite_app/global/my_app.dart';

class TesteScreen extends StatefulWidget {
  const TesteScreen({Key key}) : super(key: key);

  @override
  State<TesteScreen> createState() => _TesteScreenState();
}

class Shopping {
  String item;
  int price;
  String date;

  Shopping({this.item, this.price, this.date});

  Shopping.fromJson(Map<String, dynamic> json) {
    item = json['item'];
    price = json['price'];
    date = json['date'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['item'] = this.item;
    data['price'] = this.price;
    data['date'] = this.date;
    return data;
  }
}

class LocalStorage {
  Future<String> get(String item) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(item);
  }

  Future<bool> set(String item, dynamic data) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.setString(item, json.encode(data));
  }

  Future<bool> remove(String item) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.remove(item);
  }
}

class _TesteScreenState extends State<TesteScreen> {
  final formatDate = new DateFormat.yMMMMd('pt_BR');
  Future<List<Shopping>> _future;
  List<Shopping> list = [];

  load() async {
    String data = await LocalStorage().get("Shopping");

    if (data != null) {
      List<dynamic> lista = json.decode(data) as List;
      list = lista.map((shopping) => Shopping.fromJson(shopping)).toList();
    }

    _future = Future.value(list);
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Shopping>>(
        future: _future,
        builder: (context, snapshot) {
          if (snapshot.hasData)
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                Shopping shopping = snapshot.data[index];

                return ListTile(
                  title: Text(shopping.item),
                  subtitle: Text("${shopping.price}"),
                  trailing: Text("${formatDate.format(DateTime.parse(shopping.date))}"),
                );
              },
            );

          return CircularProgressIndicator();
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          list.add(Shopping(item: "test_${list.length + 1}", price: list.length + 1, date: DateTime.now().toString()));
          _future = Future.value(list);
          LocalStorage().set("Shopping", list);
          setState(() {});
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

相关问题