In Flutter, you can access variables from stateful widget class with the widget keyword like this:
class ChildPage extends StatefulWidget {
final String someText;
const ChildPage({Key? key, required this.someText}) : super(key: key);
@override
_ChildPageState createState() => _ChildPageState();
}
class _ChildPageState extends State<ChildPage> {
@override
Widget build(BuildContext context) {
return Center(
child: Text(widget.someText),
);
}
}
But in some cases, you may need to get the variables from the stateful widget before Widget build(BuildContext context). How to do so? The solution is to use the initState method.Advertisements
class ChildPage extends StatefulWidget {
final String someText;
const ChildPage({Key? key, required this.someText}) : super(key: key);
@override
_ChildPageState createState() => _ChildPageState();
}
class _ChildPageState extends State<ChildPage> {
late String displayText;
@override
void initState() {
displayText = widget.someText + " " + "Some extra text!";
super.initState();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(displayText),
);
}
}
The Full Example
Screenshot:
The complete code in main.dart:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: const SafeArea(
child: ChildPage(
someText: 'Have a nice day!',
),
),
);
}
}
class ChildPage extends StatefulWidget {
final String someText;
const ChildPage({Key? key, required this.someText}) : super(key: key);
@override
_ChildPageState createState() => _ChildPageState();
}
class _ChildPageState extends State<ChildPage> {
late String displayText;
@override
void initState() {
displayText = widget.someText + " " + "Some extra text!";
super.initState();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(displayText),
);
}
}
Hope this helps. Further reading:
- Flutter: Columns with Percentage Widths
- Flutter: Make Text Clickable like Hyperlinks on the Web
- How to Add a Drop Shadow to Text in Flutter
- Flutter: Dismiss Keyboard when Tap Outside Text Field
- Flutter TextField: Styling labelText, hintText, and errorText
AdvertisementsYou can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.