Home > Software engineering >  Flutter pass value to Stateful Widget
Flutter pass value to Stateful Widget

Time:06-19

When I want to call a widget within a container like this:

child: printer(text: 'test'),

How do I have to design the printer class to accept the text property. I'm new to Dart and didn't found anything on google.

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

  @override
  State<printer> createState() => _printerState();
}

class _printerState extends State<printer> {
  @override
  Widget build(BuildContext context) {
    return Text(text);
  }
}

CodePudding user response:

class printer extends StatefulWidget {
   final String text;
     const printer({Key? key,required this.text}) : super(key: key);
     @override
     State<printer> createState() => _printerState();
   }
   
  class _printerState extends State<printer> {
     @override
     Widget build(BuildContext context) {
       return Text(widget.text);
     }
   }

this will work, but its better to keep it in stateless widget or if it needs to rebuild declare the string in state and reassign value of the string and then call setState.

CodePudding user response:

we can learn passing values to Stateful Widget from the default counter app created with the flutter creat command, and observe how the Title is passed to the MyHomePage widget. enter image description here

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 MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
  • Related