Saving variables to a file - Flutter

1,323

You can use https://pub.dartlang.org/packages/path_provider to get a temp or app docs directory and then just create a file there

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'); 
Share:
1,323
Jake
Author by

Jake

Work email: jake(at)squaredsoftware.co.uk Please support me by downloading my new iOS application, travelrecce!

Updated on December 05, 2022

Comments

  • Jake
    Jake over 1 year

    I've been looking for a piece of code to save a specified variable to a text file. Ideally this would work by simply pressing a button.

    This is the code I would like to implement this into, so that on the far right of each listview item I can press an icon button and execute the aforementioned code.

    If anyone has any ideas on how to achieve this, I would be grateful for any advice.

    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);
                    },
                  ),
                )
              ],
            )
          );
      }
    

    Thank you for your time.

    Edit:

    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,
        );
      }
    

    Second Edit:

    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');  
    
      }
    
  • Jake
    Jake almost 6 years
    Thanks for the quick reply, any idea of how to get this to execute on a button press? Thanks
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    new FlatButton(onPressed: () { /* above code here */ }, child: const Text('press me'))
  • Jake
    Jake almost 6 years
    Brilliant, one last question though. Where would I implement the button into the widget: _cryptoWidget that I've pasted above? Thanks
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    Not sure, probably inside _getListItemUi() but don't know how it liiks like.
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    Can you please edit your question and add the code there. Code in comments is unrradable.
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    Hard to tell. Perhaps new Row(children: [_getSubtitleText(currency.price_usd, currency.percent_change_1h), _getSaveValueButton()]),
  • Jake
    Jake almost 6 years
    Can you please check the second edit, would this work? Also, await just after appDocDir = is highlighted red as it's undefined and not marked with async - any fix ideas? Thank you
  • Richard Heap
    Richard Heap almost 6 years
    Add the async keyword onPressed: () async { D...
  • Jake
    Jake almost 6 years
    Hey Gunter, Richard. This is an old post but where can I find the location of the file made upon button press?
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    @Jake what is "the file"?
  • Jake
    Jake almost 6 years
    When the user presses a button, the buttons specific name is stored to a .txt file. The file should be in my Path/ directory but I can’t find it
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    @Jake don't know why you expect it to be in "my Path/ directory". You need to specify the path when you create the file and then it will be created there. To get a valid path, you can use the path_provider package.
  • Jake
    Jake almost 6 years
    Looking at your original answer above, it looks like it’s saved to (‘$appDocPath/my_file.txt’) but I’ve got no clue from there
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    @Jake so you are using appDocPath? If you don't get an error the file has to be there. You can use print(myFile.absolute.path) to get the resulting path. You can also try to read after write and print the output to check the file was actually created. If this works then the problem can only be somewhere else.
  • Jake
    Jake almost 6 years
    I'm Using String appDocPath = appDocDir.path; if that's what you mean. Also with print(myFile.absolute.path); I'm getting an error that myFile is an undefined name.
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    That means that myFile is not in scope where you run print(myFile.absolute.path). Please create a new question with more code. Comments are cumbersome for this purpose.
  • Jake
    Jake almost 6 years
    Okay sure, what code should I include in the new question?
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    Ideally you would create a new Flutter project and add to lib/main.dart only the minimal code necessary to reproduce and then post the content of this lib/main.dart.
  • Jake
    Jake over 5 years
    What should the new question be? I'm thinking something like: myFile not in scope when I run print(myFile.absolute.path)
  • Günter Zöchbauer
    Günter Zöchbauer over 5 years
    Add the code that allows to reproduce the problem, describe what the current behavior is and what the expected behavior is. That should do. The title is not that important and can be adjusted later.