Как прочитать txt файл из хранилища (Flutter)? - PullRequest
0 голосов
/ 06 августа 2020

Я хочу прочитать файл конфигурации из папки на моем телефоне. Но мне удается прочитать часть файла, и я хочу прочитать весь файл. Любые идеи о том, как сделать это правильно?

Вот мой код:

import 'dart:io';

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

import 'package:flutter/services.dart';

import 'package:ext_storage/ext_storage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // String _platformVersion = 'Unknown';
  String _configFile = 'No Data';

  static Future<String> get _getPath async {
    final localPath = await ExtStorage.getExternalStoragePublicDirectory(
        ExtStorage.DIRECTORY_DOWNLOADS);
    return localPath;
  }

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

  static Future<String> readConfig() async {
    try {
      final file = await _localFile;
      // Read the file.
      String contents = await file.readAsString();
      return contents;
    } catch (e) {
      // If encountering an error, return 0.
      return "error";
    }
  }

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    if (await FlutterOpenvpn.init(
      localizedDescription: "ExampleVPN",
      providerBundleIdentifier:
          "com.topfreelancerdeveloper.flutterOpenvpnExample.RunnerExtension",
    )) {
      await FlutterOpenvpn.lunchVpn(
         _configFile,
        (isProfileLoaded) => print('isProfileLoaded : $isProfileLoaded'),
        (vpnActivated) => print('vpnActivated : $vpnActivated'),
        //expireAt: DateTime.now().add(Duration(seconds: 30)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('OpenVPN connect Test'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              IconButton(
                  iconSize: 48.0,
                  splashColor: Colors.greenAccent,
                  onPressed: _startBtnVpn,
                  icon: Icon(Icons.play_arrow)),
              IconButton(
                iconSize: 48.0,
                splashColor: Colors.greenAccent,
                icon: Icon(Icons.stop),
                onPressed: _stopBtnVPN,
              ),
              IconButton(
                  iconSize: 48.0,
                  splashColor: Colors.greenAccent,
                  icon: Icon(Icons.cloud),
                  onPressed: () {
                    readConfig().then((value) {
                      setState(() {
                        _configFile = value;
                        print(_configFile);
                      });
                    });
                  }),
            ],
          ),
        ),
      ),
    );
  }

  void _startBtnVpn() {
    setState(() {
      initPlatformState();
    });
  }

  void _stopBtnVPN() {
    FlutterOpenvpn.stopVPN();
  }
}

КОНСОЛЬ ОТЛАДКИ:

I/flutter (17341): "dev tun\n" +
I/flutter (17341):             "proto udp\n" +
I/flutter (17341):             "remote public-vpn-255.opengw.net 1195\n" +
I/flutter (17341):             ";http-proxy-retry\n" +
I/flutter (17341):             ";http-proxy [proxy server] [proxy port]\n" +
I/flutter (17341):             "cipher AES-128-CBC\n" +
I/flutter (17341):             "auth SHA1\n" +
I/flutter (17341):             "resolv-retry infinite\n" +
I/flutter (17341):             "nobind\n" +
I/flutter (17341):             "persist-key\n" +
I/flutter (17341):             "persist-tun\n" +
I/flutter (17341):             "client\n" +
I/flutter (17341):             "verb 3\n" +
I/flutter (17341):             "<ca>\n" +
I/flutter (17341): "-----BEGIN CERTIFICATE-----\n" +
I/flutter (17341): "MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB\n" +
I/flutter (17341): "iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n" +
I/flutter (17341): "cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n" +
I/flutter (17341): "BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw\n" +
I/flutter (17341): "MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV\n" +
I/flutter (17341): "BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU\n" +
I/flutter (17341): "aGUgVVNFUlR

1 Ответ

0 голосов
/ 06 августа 2020

Проблема в том, что функция print имеет ограничение на вывод вывода на консоль и не печатает длинные строки полностью. Попробуйте установить точку останова с помощью IDE или редактора и проверьте значение, прочитанное из файла.

...