将数据存储到本地存储时获取Null异常

时间:2019-02-04 06:41:05

标签: dart flutter

我尝试遵循以下dart read/write tutorialstackoverflow answer 来创建一个dart文件,用于将数据读取和写入本地存储。

这是我的课程:

import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

class FavoritesStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/favorites.txt');
  }

  Future<List<String>> readFavoriteList() async {
    try {
      final file = await _localFile;

      // Read the file
      List<String> contents = await file.readAsLines();

      return contents;
    } catch (e) {
      // If we encounter an error, return null
      return null;
    }
  }

  Future<File> writeFavoriteList(String favorite) async {
    final file = await _localFile;
    print("local file" + file.toString());
    // Write the file
    return file.writeAsString('$favorite');
  }

}

然后我在另一个类中调用write方法,如下所示:

    class FavoriteWidget extends StatefulWidget {
      final dish_name;
      @override
      _FavoriteWidgetState createState() => _FavoriteWidgetState();
      final FavoritesStorage storage;
      FavoriteWidget(this.dish_name, {Key key, @required this.storage})
          : super(key: key);
    }

    class _FavoriteWidgetState extends State<FavoriteWidget> {
      bool _isFavorited = false;

      // #docregion _toggleFavorite
      void _toggleFavorite() {
        setState(() {
          if (_isFavorited) {


            _isFavorited = false;
          } else {
            //Add to local storage   
            widget.storage.writeFavoriteList(widget.dish_name);
            _isFavorited = true;
          }
        });
      }

      @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          icon: (_isFavorited
              ? Icon(Icons.favorite, size: 35, color: Colors.green)
              : Icon(Icons.favorite_border, size: 35, color: Colors.green)),
          color: Colors.red[500],
          onPressed: _toggleFavorite,
        ),
        Container(
          margin: const EdgeInsets.only(top: 8.0),
          child: Text(
            "FAVORITE",
            style: TextStyle(
              fontSize: 12.0,
              fontWeight: FontWeight.w400,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }
}

但是,我收到以下错误消息:

  

在null上调用了方法'writeFavoriteList'。

0 个答案:

没有答案