In Flutter, how do I pass data into a Stateless Widget?

Sharon picture Sharon · Sep 20, 2019 · Viewed 22.6k times · Source

I'm trying to build my first Flutter app, and have run into difficulty with passing data into Stateless Widgets. I have the following classes:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'App Title',
      theme: new ThemeData(
        primarySwatch: Colors.green,
      ),
      home: new MainBody(),
    );
  }
}


class MainBody extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Padding(
        padding: const EdgeInsets.only(left: 20.0, right: 20.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new TimeCheck(),
          ],
        ),
      ),
    );
  }
}

TimeCheck is a Stateful Widget. Basically, I want to be able to set some values at the start, and then pass them along to TimeCheck, via MainBody. Everything I read shows how to pass data into Stateful Widgets, but is it possible to pass it through a Stateless Widget?

I recognise I may be taking the wrong approach, so in case it helps, what I'd ultimately like to do is have a "settings" page where the user can set the values for the data (a string and some numbers), and then those values get passed to TimeCheck where they're used to generate the display.

I'd also like to be able to save the user-set values if possible, so they don't have to enter them each time, and then I'd like to be able to read them in when TimeCheck is instantiated.

Answer

Rodrigo Bastos picture Rodrigo Bastos · Sep 20, 2019

Yes you can do this simply by passing the info to the constructor. Something like this:

 class MyApp extends StatelessWidget {
  MyApp(this.yourData);

  final int yourData;
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'App Title',
      theme: new ThemeData(
        primarySwatch: Colors.green,
      ),
      home: new MainBody(yourData),
    );
  }
}


class MainBody extends StatelessWidget {
  MainBody(this.yourData);

  final int yourData;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Padding(
        padding: const EdgeInsets.only(left: 20.0, right: 20.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new TimeCheck(yourData),
          ],
        ),
      ),
    );
  }
}