Home > database >  Flutter: Gridview not updating with expected values
Flutter: Gridview not updating with expected values

Time:07-01

My app should pick a directory and list the files of the directory in cards.

Right now it does that but it has a little inconvenient, it lists the files from the "previous" directory. For example if the first picked dir is D:\AM it would lists the files at the default path location (in my code an empty String), but if I press the button again and choose a different directory like D:\AM\test(expecting a single text file) it would list the files of D:\AM. I change the app title to match the picked directory at button press but as you can see it lists the files from another directory(previous picked directory D:\AM).

What I get: incorrect

What I should get from the start (got this after picking the D:\AM\test dir again) correct

My code:

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'dart:io';
class Demo3 extends StatefulWidget {
  const Demo3({Key? key}) : super(key: key);

  @override
  _Demo3State createState() => _Demo3State();
}

class _Demo3State extends State<Demo3> {
  late String path = '';
  var files = [];

  void selectDir() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

    if (selectedDirectory == null) {
      setState(() {
        path  = "";
      });

    }
    else{
      setState(() {
        path = selectedDirectory;
      });

    }
    print(path);
  }


  void listFiles(String paths) async {
    var dir = Directory(paths);
    List<FileSystemEntity> entities = await dir.list().toList();
    setState(() {
      files = entities;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$path'),
        actions: [
          IconButton(
            onPressed: () {
              selectDir();
              listFiles(path);
            },
            icon: const Icon(Icons.browse_gallery),
          ),
        ]
      ),
      body: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3
          ),
          itemCount: files.length,
          itemBuilder:(BuildContext context, int index){
            var test = files[index];
            return Card(
              child: Text('$test'),
            );
          }
      )
    );
  }
}

Any help is appreciated, thanks!

CodePudding user response:

try this, just replaced listFiles() inside selectDir rather than in button tap.

void selectDir() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
    print(selectedDirectory);
    if (selectedDirectory == null) {
      setState(() {
        path = "";
      });
    } else {
      setState(() {
        path = selectedDirectory;
        listFiles(path);
      });
    }
    print(path);
  }


  • Related