flutterdart

Flutter state variable pass to widget


I wrote a simple dart program to test pass of int

a(int x) {
  x++;
  print(x);
}

main() {
  int x = 1;
  a(x);
  print(x);
}

Output:

2 1

Which means there are 2 separate int, after pass they don't effect each other.


But in the following flutter program, seems state's int variable effect widget's int variable after pass via constructor.

import 'package:flutter/material.dart';

class CounterDisplay extends StatelessWidget {
  const CounterDisplay({required this.count, super.key});

  final int count;

  @override
  Widget build(BuildContext context) {
    return Text('Count: $count');
  }
}

class CounterIncrementor extends StatelessWidget {
  const CounterIncrementor({required this.onPressed, super.key});

  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: const Text('Increment'),
    );
  }
}

class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    setState(() {
      ++_counter;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        CounterIncrementor(onPressed: _increment),
        const SizedBox(width: 16),
        CounterDisplay(count: _counter),
      ],
    );
  }
}

void main() {
  runApp(
    const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Counter(),
        ),
      ),
    ),
  );
}

Above code is from https://docs.flutter.dev/ui#changing-widgets-in-response-to-input, the 2nd part.

Since CounterDisplay(count: _counter) pass an int to constructor. I thought after pass, there should be 2 separate int, why would the change of _counter from _CounterState effect count from CounterDisplay ?


Solution

  • The reason: the _counter value from _CounterState affects the count value in CounterDisplay is related to how Flutter's widget tree and state management work, rather than how primitive types (like int) are passed in Dart.