Home > front end >  How to change text in widget on button click in Dart/Flutter?
How to change text in widget on button click in Dart/Flutter?

Time:06-30

I need to change the text in this widget when the button is clicked.

That is, every time I click on the button, the text changes to what is in the first column of my lit. First the first line, then the second line, and so on until the end.

Here is the code:

// CSV Experiment route
class CSVExperimentRoute extends StatelessWidget {
  const CSVExperimentRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'CSV Experiment',
      home: ListFromCSV(),
    );
  }
}

class ListFromCSV extends StatefulWidget {
  const ListFromCSV({Key? key}) : super(key: key);

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

class _ListFromCSVState extends State<ListFromCSV> {
  List<List<dynamic>> _data = [];

  // This function is triggered when my button is pressed
  void _loadCSV() async {
    final _rawData = await rootBundle.loadString("files/Text.csv");
    List<List<dynamic>> _listData =
    const CsvToListConverter().convert(_rawData);
    setState(() {
      _data = _listData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("My CSV Attempt"),
      ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              Color(0xFF0D47A1),
                              Color(0xFF1976D2),
                              Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(16.0),
                        primary: Colors.white,
                        textStyle: const TextStyle(fontSize: 20),
                      ),
                      onPressed: _loadCSV,
                      child: const Text('Click me to change Text'),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              Color(0xFF0D47A1),
                              Color(0xFF1976D2),
                              Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(16.0),
                        primary: Colors.white,
                        textStyle: const TextStyle(fontSize: 20),
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => const YetAnotherRoute()),
                        );
                      },
                      child: const Text('Button 2'),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              Color(0xFF0D47A1),
                              Color(0xFF1976D2),
                              Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(16.0),
                        primary: Colors.white,
                        textStyle: const TextStyle(fontSize: 20),
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => const CSVRoute()),
                        );
                      },
                      child: const Text('Button 3'),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              // Color(0xFF0D47A1),
                              // Color(0xFF1976D2),
                              // Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Text(
                      'Item from CSV',
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    )
                  ],
                ),
              ),

            ],
          ),
        )
      // Display the contents from the CSV file
      // body: ListView.builder(
      //   itemCount: _data.length,
      //   itemBuilder: (_, index) {
      //     return Card(
      //       margin: const EdgeInsets.all(3),
      //       color: index == 0 ? Colors.amber : Colors.white,
      //       child: ListTile(
      //         leading: Text(_data[index][0].toString()),
      //         // title: Text(_data[index][1]),
      //         // trailing: Text(_data[index][2].toString()),
      //       ),
      //     );
      //   },
      // ),
    );
  }
}

And here is a schematic representation of what I want:

Screenshot

Thanks in advance for your help.

Edit1. If added to text

Text(
                      _data[0].toString() != null ? 
                      _data[0].toString() : '',
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    )

, then I get the following error:

enter image description here

Edit2. Here is a sample of how the .csv file looks like for testing purposes. This is a list of lists.

enter image description here

CodePudding user response:

If I understand it right you can simply access the list on index 0 if this is your correct data.

Text(
                      _data[0].toString() != null ? 
                      _data[0].toString() : '',
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    )

CodePudding user response:

You are accessing List of List in the wrong way. The correct way would be something like this: _data[0][_listCount];

A better approach would be: (EDIT: I have put all the code now)

class CSVExperimentRoute extends StatelessWidget {
  const CSVExperimentRoute({key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'CSV Experiment',
      home: ListFromCSV(),
    );
  }
}

class ListFromCSV extends StatefulWidget {
  const ListFromCSV({Key? key}) : super(key: key);

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

class _ListFromCSVState extends State<ListFromCSV> {
  List<List<dynamic>> _data = [
    [""]
  ];
  int _listCount = 0;
  bool _isFirstLoad = true;

  // This function is triggered when my button is pressed
  void _loadCSV() async {
    List<dynamic> test = ["First", "Second", "Third", "Fourth"];
    List<List<dynamic>> _listData = [];
    _listData.add(test);

    setState(() {
      _data = _listData;
      _listCount < test.length - 1
          ? _isFirstLoad
              ? _isFirstLoad = false
              : _listCount  
          : _listCount;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("My CSV Attempt"),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              Color(0xFF0D47A1),
                              Color(0xFF1976D2),
                              Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(16.0),
                        primary: Colors.white,
                        textStyle: const TextStyle(fontSize: 20),
                      ),
                      onPressed: _loadCSV,
                      child: const Text('Click me to change Text'),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              Color(0xFF0D47A1),
                              Color(0xFF1976D2),
                              Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(16.0),
                        primary: Colors.white,
                        textStyle: const TextStyle(fontSize: 20),
                      ),
                      onPressed: () {},
                      child: const Text('Button 2'),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              Color(0xFF0D47A1),
                              Color(0xFF1976D2),
                              Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(16.0),
                        primary: Colors.white,
                        textStyle: const TextStyle(fontSize: 20),
                      ),
                      onPressed: () {},
                      child: const Text('Button 3'),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Stack(
                  children: <Widget>[
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: <Color>[
                              // Color(0xFF0D47A1),
                              // Color(0xFF1976D2),
                              // Color(0xFF42A5F5),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Text(
                      _data[0][_listCount],
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    )
                  ],
                ),
              ),
            ],
          ),
        )
        // Display the contents from the CSV file
        // body: ListView.builder(
        //   itemCount: _data.length,
        //   itemBuilder: (_, index) {
        //     return Card(
        //       margin: const EdgeInsets.all(3),
        //       color: index == 0 ? Colors.amber : Colors.white,
        //       child: ListTile(
        //         leading: Text(_data[index][0].toString()),
        //         // title: Text(_data[index][1]),
        //         // trailing: Text(_data[index][2].toString()),
        //       ),
        //     );
        //   },
        // ),
        );
  }
}
  • Related