Using BuildContext outside build function

You can use builder widget. ... https://api.flutter.dev/flutter/widgets/Builder-class.html


You have access to BuildContext inside build method.

So you can move your place() function inside build.

Widget build(BuildContext context) {
  page(text, color) {
    return Container(
      color: color,
      child: Align(
        alignment: Alignment(0, 0.5),
        child: Text(
          text,
          style: Theme.of(context).textTheme.headline,
        ),
      ),
    );
  }

  return MaterialApp(
    home: Scaffold(
      appBar: AppBar(),
      body: Column(
        children: <Widget>[
          page('Page 1', Colors.orange),
          page('Page 2', Colors.green),
        ],
      ),
    ),
  );
}

Also in cases like yours a good pattern would be to create your own reusable Page widget and pass your parameters via constructor.

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Column(
          children: <Widget>[
            _Page(text: 'Page 1', color: Colors.orange),
            _Page(text: 'Page 2', color: Colors.green),
          ],
        ),
      ),
    );
  }
}

class _Page extends StatelessWidget {
  const _Page({
    Key key,
    @required this.color,
    @required this.text,
  }) : super(key: key);

  final Color color;
  final String text;
  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      child: Align(
        alignment: Alignment(0, 0.5),
        child: Text(
          text,
          style: Theme.of(context).textTheme.headline,
        ),
      ),
    );
  }
}

Tags:

Dart

Flutter