【问题标题】:Errors with writing string to a text file将字符串写入文本文件时出错
【发布时间】:2020-05-06 13:17:43
【问题描述】:

我一直在尝试通过按下按钮将字符串记录到文本文件中。这是我的代码:

onPressed: () async {
                        File('dates.txt').writeAsStringSync('${_date.month}/${_date.day}/${_date.year}');
                      }),

我不知道为什么它不起作用,我想我错过了一些东西。 感谢您的宝贵时间!

【问题讨论】:

  • 您有任何错误吗?请将它们包括在问题中。
  • 你在哪里执行??请提供更多信息。我认为如果您在浏览器中运行它,则上下文中没有 dates.txt。
  • 我没有收到任何错误,我正在从 Android Studio SDK 运行它。
  • 定义“不工作”。当您使用writeAsStringSync 同步写入文件时,async 也是多余的。
  • 不是写入文本文件,按下按钮时文本文件为空。

标签: flutter dart


【解决方案1】:

我找到了解决这个问题的方法。总而言之,我查看了 Flutter Docs 中的一个页面 (https://flutter.dev/docs/cookbook/persistence/reading-writing-files) 发现我只需要添加一些文件读取/写入所需的期货并将它们应用到我的“onPressed”函数中。

这是我的最终代码:

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

void main() => runApp(MaterialApp(
      home: FirstScreen(),
    ));

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new Scaffold(
      appBar: new AppBar(
        centerTitle: true,
        title: new Text("My School Calendar"),
      ),
      body: Container(
          child: Align(
        alignment: Alignment(0, -0.9),
        child: FlatButton.icon(
          color: Colors.teal,
          icon: Icon(Icons.plus_one), //`Icon` to display
          label: Text('Create new entry'), //`Text` to display
          onPressed: () {
            Navigator.push(
              ctxt,
              new MaterialPageRoute(builder: (ctxt) => new SecondScreen()),
            );
          },
        ),
      )),
    );
  }
}

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  DateTime _date = new DateTime.now();
  TimeOfDay _time = new TimeOfDay.now();

  Future<Null> _selectDate(BuildContext ctxt) async {
    final DateTime picked = await showDatePicker(
      context: ctxt,
      initialDate: _date,
      firstDate: new DateTime.now().subtract(Duration(days: 1)),
      lastDate: new DateTime.now().add(Duration(days: 365)),
    );
    if (picked != null && picked != _date) {
      print('Date selected: ${_date.toString()}');
      setState((){
        _date = picked;
      });
    }
  }

  Future<Null> _selectTime(BuildContext ctxt) async {
    final TimeOfDay picked = await showTimePicker(
        context: ctxt,
        initialTime: _time
    );
    if (picked != null && picked != _time) {
      print('Date selected: ${_time.toString()}');
      setState((){
        _time = picked;
      });
    }
  }

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

    return directory.path;
  }

  Future<int> readDate() async {
    try {
      final file = await _localFile;

      // Read the file
      String contents = await file.readAsString();
      print('Date read from file: ' + contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

  Future<File> writeDate() async {
    final file = await _localFile;

    // Write the file.
    String dateToWrite = '${_date.month}/${_date.day}/${_date.year}';
    return file.writeAsString(dateToWrite);
  }

  final myController = TextEditingController();
  @override
  Widget build(BuildContext ctxt) {
    return MaterialApp(
        home: Scaffold(
            appBar: new AppBar(
              title: new Text("Enter assignment details"),
            ),
            body: Container(
              margin: const EdgeInsets.only(top: 10.0),
              child: Align(
                alignment: Alignment(0, -0.9),
                child: Column(children: <Widget>[
                  TextField(
                    controller: myController,
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.black,
                          ),
                          borderRadius: BorderRadius.all(Radius.circular(15)),
                        ),
                        hintText: 'Enter assignment name'),
                  ),
                  FlatButton.icon(
                      color: Colors.redAccent,
                      icon: Icon(Icons.calendar_today), //`Icon` to display
                      label: Text('Select date'), //`Text` to display
                      onPressed: () {
                        _selectDate(ctxt);
                      }),
                  Text('Date selected: ${_date.month}/${_date.day}/${_date.year}'),
                  FlatButton.icon(
                      color: Colors.grey,
                      icon: Icon(Icons.access_time), //`Icon` to display
                      label: Text('Select time'), //`Text` to display
                      onPressed: () {
                        _selectTime(ctxt);
                      }),
                  Text('Time selected: ${_time.hour}:${_time.minute}'),
                  FlatButton.icon(
                      color: Colors.lightBlueAccent,
                      icon: Icon(Icons.check_box), //`Icon` to display
                      label: Text('Submit'), //`Text` to display
                      onPressed: () {
                        writeDate();
                        readDate();
                      }),
                ]),
              ),
            )));
  }
}

希望这对其他人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2013-07-28
    • 1970-01-01
    相关资源
    最近更新 更多