简体   繁体   中英

Passing variable value from state to another widget

I am struggling with one simple case and it would be lovely if someone could help here.

Let's say that I have some stateful widget . In its state I define a variable (might be of any type) and this variable is later changed through setState() method, where I dynamically assign its value based on some certain criteria. Evertyhing until this point is conducted within one class.

What if I would like to access the value of this variable from another class (totally different page ) and if its value changes, rebuild it? Could you please also give me some examples?

Thanks in advance!

That's exactly why State MANAGEMENT exists. To manage your state through your app. There are many different options to follow See: https://flutter.dev/docs/development/data-and-backend/state-mgmt/options

You can use provider package in that case. In yaml file add, provider: ^4.3.2+4

class HomeApp extends StatefulWidget {
  @override
  _HomeAppState createState() => _HomeAppState();
}

class _HomeAppState extends State<HomeApp> {
  Counter _counterProvider;

  @override
  void initState() {
    super.initState();
    _counterProvider = Provider.of(context, listen: false);
  }

  void updateCounter() {
    _counterProvider.setCount();
  }

  @override
  Widget build(BuildContext context) {
    Counter _counterProvider = Provider.of(context);
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              child: Text(
                _counterProvider.count.toString(),
                style: TextStyle(
                  fontSize: 22,
                ),
              ),
            ),
            RaisedButton(
              onPressed: updateCounter,
              child: Text('Click'),
            ),
          ],
        ),
      ),
    );
  }
}
// class for storing data(Counter.dart)
import 'package:flutter/material.dart';

class Counter extends ChangeNotifier { // create a common file for data
  int _count = 0;

  int get count => _count;

  void setCount() {
    _count++;
    notifyListeners();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM