How to import data to CSV getting from facebook API and export the CSV file using flutter

Viewed 156

I have the below Simple code that make user authentication via Facebook API and read the default user information.

This is the code snippet I have:

import 'package:flutter/material.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as JSON;

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  bool _isLoggedIn = false;
  Map userProfile;
  final facebookLogin = FacebookLogin();

  _loginWithFB() async {
    final result = await facebookLogin.logIn(['email']);

    switch (result.status) {
      case FacebookLoginStatus.loggedIn:
        final token = result.accessToken.token;
        final graphResponse = await http.get(Uri.parse(
            'https://graph.facebook.com/v10.0/me?fields=id,name,picture,email,name_format,birthday,hometown&access_token=${token}'));

        final profile = JSON.jsonDecode(graphResponse.body);
        print(profile);
        setState(() {
          userProfile = profile;
          _isLoggedIn = true;
        });
        break;

      case FacebookLoginStatus.cancelledByUser:
        setState(() => _isLoggedIn = false);
        break;
      case FacebookLoginStatus.error:
        setState(() => _isLoggedIn = false);
        break;
    }
  }

  _logout() {
    facebookLogin.logOut();
    setState(() {
      _isLoggedIn = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        body: Center(
            child: _isLoggedIn
                ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.network(
                  userProfile["picture"]["data"]["url"],
                  height: 100.0,
                  width: 100.0,
                ),
                Text(userProfile["id"]),
                Text(userProfile["name"]),
                Text(userProfile["email"]),
                Text(userProfile["name_format"]),
                Text(userProfile["birthday"] ?? 'Birthday: empty'),
                Text(userProfile["hometown"] ?? 'Hometown: empty'),
                OutlinedButton(
                  child: Text("Logout"),
                  onPressed: () {
                    _logout();
                  },
                )
              ],
            )
                : Center(
              child: OutlinedButton(
                child: Text("Login with Facebook"),
                onPressed: () {
                  _loginWithFB();
                },
              ),
            )),
      ),
    );
  }
}

as I need to export a CSV file to be something like the below image: enter image description here

1 Answers

Use the CSV Plugin.

Step 1: add CSV plugin in the pubspec.yaml file

csv: ^5.0.0

Step 2: create CsvController.dart file and add the following code for CsvController

class CsvController {

  static Future<File> getCsvFromList(List<List<dynamic>> csvDataList) async {
    try {
      String csvDataString = const ListToCsvConverter().convert(csvDataList);
      File csvFile = await _saveFile(csvDataString);
      return csvFile;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  static Future<File> getCsvFromString(String csvString) async {
    try {
      File csvFile = await _saveFile(csvString);
      return csvFile;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  static Future<String> _getFilePath(String fileName) async {
    Directory appDocumentsDirectory = await getExternalStorageDirectory(); // 1
    String appDocumentsPath = appDocumentsDirectory.path; // 2
    String filePath = '$appDocumentsPath/$fileName.csv'; // 3
    return filePath;
  }

  static Future<File> _saveFile(String fileDataString, {index = 0}) async {
    try {
      File file = File(await _getFilePath(
          "${General.getDate().millisecondsSinceEpoch}" +
              (index > 0 ? "($index)" : "")));
      if (!file.existsSync()) {
        // 1
        file.writeAsStringSync(fileDataString); // 2
        return file;
      } else {
        return _saveFile(fileDataString, index: index + 1);
      }
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

Step 3: just call the respective function according to your data like below:

//if you have comma separated string already 
File csvFile = await CsvController.getCsvFromString(your_comma_separated_String);
if(csvFile != null){
    print("File created here :"+csvFile.path);
}else{
    print("file not created");
}

//if you have data in List<List<dynamic>> format or you can convert to this format

//for Example, To create a csv file like this
     // 1,2,3
     // "A","B","C"
     // 7,8,9

//in Your case 
List<List<dynamic>> csvData= [
["ID","username","email"],
[123,"user 1","user1@email.com"]
]

// create a list and just send it like below:
List<List<dynamic>> csvData=[
[1,2,3],
["A","B","C"],
[7,8,9]
];

File csvFile = await CsvController.getCsvFromList(csvData);
if(csvFile != null){
    print("File created here :"+csvFile.path);
}else{
    print("file not created");
}

NOTE: This class also takes care of the file that exists then it will just add the number to its name and will create it like file downloading in the browser.

For example,

File.csv exists then it will create File(1).csv

Related