【问题标题】:Saving variables to a file - Flutter将变量保存到文件 - Flutter
【发布时间】:2025-01-05 08:20:02
【问题描述】:

我一直在寻找一段代码来将指定的变量保存到文本文件。理想情况下,只需按下按钮即可。

这是我想要实现的代码,以便在每个列表视图项的最右侧上,我可以按下图标按钮并执行上述代码。

如果有人对如何实现这一目标有任何想法,我将不胜感激。

Widget _cryptoWidget() {
    return new Container(
        child: new Column(
          children: <Widget>[
            new Flexible(
              child: new ListView.builder(
                itemCount: _currencies.length,
                itemBuilder: (BuildContext context, int index) {
                  final int i = index ~/ 2;
                  final Crypto currency = _currencies[i];
                  final MaterialColor color = _colors[i % _colors.length];
                  if (index.isOdd) {
                    return new Divider();
                  }
                  return _getListItemUi(currency, color);
                },
              ),
            )
          ],
        )
      );
  }

感谢您的宝贵时间。

编辑:

ListTile _getListItemUi(Crypto currency, MaterialColor color) {
    return new ListTile(
      leading: new Image.network("http://cryptoicons.co/32@2x/color/"+currency.symbol.toLowerCase()+"@2x.png"),
      title: new Text(currency.name,
          style: new TextStyle(fontWeight: FontWeight.bold)),
      subtitle:
      _getSubtitleText(currency.price_usd, currency.percent_change_1h),
      isThreeLine: true,
    );
  }

第二次编辑:

Widget _getSaveValueButton() {
    new IconButton(
    icon: new Icon(Icons.add),
    onPressed: () { Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    new File('$appDocPath/my_file.txt').writeAsStringSync('myVar: $_currencies');  

  }

【问题讨论】:

    标签: android ios string file flutter


    【解决方案1】:

    您可以使用https://pub.dartlang.org/packages/path_provider 获取临时或应用文档目录,然后在其中创建一个文件

    String someVal = 'some value to write to the file'; 
    
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    new File('$appDocPath/my_file.txt').writeAsStringSync('myVar: $someVal'); 
    

    【讨论】:

    • 感谢您的快速回复,您知道如何在按下按钮时执行此操作吗?谢谢
    • new FlatButton(onPressed: () { /* above code here */ }, child: const Text('press me'))
    • 太棒了,不过还有最后一个问题。我将在哪里将按钮实现到小部件中:我在上面粘贴的 _cryptoWidget ?谢谢
    • 不确定,可能在_getListItemUi() 内部,但不知道它是什么样的。
    • 添加异步关键字onPressed: () async { D...