csvflutterdart

How can I read a csv file and pass the values to a List<String> in flutter?


Well, I'm new at flutter doesn't know how to read a csv file, my csv file has a string per line, All I want is read from csv file to a List<String> then pass to my Simpleautocompletetext widget suggestions

SimpleAutoCompleteTextField(
              key: key,
              suggestions: o,
              decoration: InputDecoration(
                labelText: 'Name',
                hintText: 'Input Name',
                icon: Icon(Icons.person),
                isDense: true,
              ),
            ),

I am follow this https://github.com/felixlucien/flutter-autocomplete-textfield/blob/master/example/lib/main.dart He has a list on the same file, but i want to import from my csv. How do I do that?


Solution

  • load csv from assets and split with new Line

    class CsvImp extends StatefulWidget {
      @override
      _CsvImp createState() => _CsvImp();
    }
    
    class _CsvImp extends State<CsvImp> {
    
      List<String> added = [];
      String currentText = "";
      List<String> csv = new List();
      GlobalKey<AutoCompleteTextFieldState<String>> key = new GlobalKey();
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
    
        loadCSV();
    
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
            appBar: new AppBar(
              title: new Text("csv"),
            ),
            body: csv.length == 0 ? new Container() :
            new SimpleAutoCompleteTextField(
              key: key,
              suggestions: csv,
              decoration: InputDecoration(
                labelText: 'Name',
                hintText: 'Input Name',
                icon: Icon(Icons.person),
                isDense: true,
              ),
            ),
    
          );
      }
    
      Future<String> loadAsset(String path) async {
        return await rootBundle.loadString(path);
      }
    
      void loadCSV() {
        loadAsset('assets/file.csv').then((String output) {
    
          setState(() {
            csv = output.split("\n");
          });
    
        });
      }
    }