How do you pass data to a widget in flutter?

To pass data to a Flutter widget we can use various methods. However, today, we’ll discuss the simplest method, so that a beginner can understand.

We’ll pass data through class constructors. We’ve been already working on Flutter latest version 2.5. After having seen a couple of articles about the changes and features of Flutter 2.5, we’ll try to pass data from one widget to the other using Flutter app template skeleton.

As we’ve seen if we run the app without tweaking the code, it shows a ListView items.

Flutter 2.5 template home page
Flutter 2.5 template home page

When we click any one of the item, it takes us to the detail page where actually we don’t pass any data.

To pass data to the detail page we need to use Navigator arguments.

As a result, when we launch the fresh app, we see the detail page like the following image:

Flutter 2.5 template detail page
Flutter 2.5 template detail page

Now, we don’t want to see such a blank page, where no data has been passed from the home page ListView items.

We want to pass data from the home page so that that data gets displayed on this detail page.

To do that, let’s create a simple Student class. Where each student has an ID, and a name.

Now, in our app, when we click on the ID of any student, the name should be displayed on the Student details page.

How do we pass data between classes in flutter?

As we’ve said earlier, the simplest method to pass data between classes in flutter is class constructor.

In our “/lib/src/models/” folder let’s have a Student class first.

class Student {
  final String id;
  final String name;
  const Student(this.id, this.name);
}

Firstly, for brevity, we need to be succinct in displaying the code snippets here. Therefore, please visit the respective GitHub Repository for the full code, if you’re interested.

Secondly, we need to instantiate a few Student objects before we pass the student details.

Without two or three students how we can show their details in the detail page?

class SampleItemListView extends StatelessWidget {
  const SampleItemListView({
    Key? key,
    this.students = const [
      Student('s1', 'John'),
      Student('s2', 'Json'),
      Student('s3', 'Maria'),
    ],
  }) : super(key: key);

  static const routeName = '/';

  final List<Student> students;
...

In this Sample Item ListView page, we’ll show the Student ID only. But, we’ll pass the name as Navigator argument.

We’ve already created three Students with their respective ID and name. As a result, it’ll not be difficult to show all the IDs in a ListView. At the same time, we can pass the name as argument also.

 body: ListView.builder(        
        restorationId: 'sampleItemListView',
        itemCount: students.length,
        itemBuilder: (BuildContext context, int index) {
          final student = students[index];

          return ListTile(
              title: Text('Student ID: ${student.id}'),
              leading: const CircleAvatar(
                // Display the Flutter Logo image asset.
                foregroundImage: AssetImage('assets/images/flutter_logo.png'),
              ),
              onTap: () {                
                Navigator.restorablePushNamed(
                  context,
                  SampleItemDetailsView.routeName,
                  arguments: student.name,
                );
              });
        },
      
),

The ListView builder counts the students number, and show only the clickable IDs on the page.

The first important part is the following one:

itemCount: students.length,
        itemBuilder: (BuildContext context, int index) {
          final student = students[index];

Next, we show the student ID with an image that we get from the assets/images folder.

title: Text('Student ID: ${student.id}'),
              leading: const CircleAvatar(
                // Display the Flutter Logo image asset.
                foregroundImage: AssetImage('assets/images/flutter_logo.png'),
              ),

And, finally, we have the on Tap method, where we pass the name of the student as an argument.

Navigator.restorablePushNamed(
                  context,
                  SampleItemDetailsView.routeName,
                  arguments: student.name,
                );

Consequently, when we run the app, we get the students IDs displayed on the home page.

Pass data through class constructor
Pass data through class constructor

How do we get data through class constructor?

To get data through class constructor, we need to have some other mechanism.

We must get the data by this line of code:

final String name = ModalRoute.of(context)!.settings.arguments as String;

Although we have got the argument as a simple String here, the functionality of ModalRoute arguments could be quite complex. We’ll see that in our next article.

However, to make this process simple, we can just have the data as a string and show that on a Text widget.

class SampleItemDetailsView extends StatelessWidget {
  const SampleItemDetailsView({Key? key}) : super(key: key);

  static const routeName = '/student_details';

  @override
  Widget build(BuildContext context) {
    final String name = ModalRoute.of(context)!.settings.arguments as String;

    return Scaffold(
      appBar: AppBar(
        title: const Text('Student Details'),
      ),
      body: Center(
        child: Container(
          margin: const EdgeInsets.all(
            20.0,
          ),
          padding: const EdgeInsets.all(
            20.0,
          ),
          child: ListView(
            children: [
              Text(
                'Student Name: $name',
                style: const TextStyle(
                  fontSize: 40.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

As a result, instead of a blank page, we can have at least the respective student’s name displayed on the details page.

Data has been passed through class constructor
Data has been passed through class constructor

In the next article, we’ll see more complex examples examples, where we can use List and Map concepts so that we can pass more data.

However, to do that we need to tweak the above code.

Until then, stay tuned.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

4 responses to “How do you pass data to a widget in flutter?”

  1. […] Flutter User Interface can pass data all the way down the tree from parent to child. We can always pass them through constructors, or use Inherited […]

  2. […] regardant l’image ci-dessus, nous pouvons comprendre que le Widget vient de commencer à changer d’état. En conséquence, il y a une animation autour du […]

  3. […] a result, we can access to the particular Hero Widget by the “tag” in any […]

  4. […] our previous article, we’ve seen how we can pass data to a widget. We’ve done that using Flutter 2.5 app template […]

Leave a Reply