Umer
Umer

Reputation: 203

how to access variable value , from a different screen in flutter?

Q1: how can i get the a certain variable value that is being used in a different screen? i am trying to change the background color of appbar and button by reading a variable that is being used on another screen ?

Explanation: I am fairly new to flutter and experimenting with different things, i have about 5 to six flutter screens and on the 5th screen there is a dropdown list which has 3 values see the code :

                 Padding(
                      padding: const EdgeInsets.symmetric(vertical: 10),
                      child: ListTile(title: Text("select one",style: TextStyle(fontfamily: "Ubuntu",
                              fontWeight: FontWeight.w200,fontSize: 18,color: Colors.black),),
                        subtitle: DropdownButton(
                          isExpanded: true,
                          items: [
                            DropdownMenuItem(child: Text("option1"),value: "option1",),
                            DropdownMenuItem(child: Text("option2"), value: "option2"),
                            DropdownMenuItem(child: Text("option3"), value: "option3"),
                          ],

i want to get these values and use them on other screens based on the selected option for example : if option 1 is selected then do this if option 2 is selected then do that

Q2: i intend to use simple if statements , once i can get the values from the screen5 , is using if statement the right way to of doing it ?

EDIT 1: i did what Nitesh suggested : this is my code in the 5th screen:

print(Value.getString());

but i am getting the error that error: The method 'getString' isn't defined for the type 'Value'.

Upvotes: 0

Views: 4483

Answers (2)

Thierry
Thierry

Reputation: 8383

I advise you to learn about State Management.

Here is a solution based on Riverpod and Flutter Hooks.

enter image description here

  1. Define a Provider (Here, a StateProvider)
final optionProvider = StateProvider<String>((ref) => options.first);
  1. Watch its state inside the build method
final _currentOption = useProvider(optionProvider).state;
  1. Modify its state
onChanged: (value) => context.read(optionProvider).state = value,

Full source code:

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

void main() {
  runApp(
    ProviderScope(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        home: HomePage(),
      ),
    ),
  );
}

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _currentOption = useProvider(optionProvider).state;
    return Scaffold(
      appBar: AppBar(
        title: Text('MyApp'),
        actions: [
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SettingsPage(),
              ),
            ),
          ),
        ],
      ),
      body: Center(child: Text('CURRENT: $_currentOption')),
    );
  }
}

class SettingsPage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _currentOption = useProvider(optionProvider).state;
    return Scaffold(
      appBar: AppBar(title: Text('Settings')),
      body: Center(
        child: DropdownButton(
          isExpanded: true,
          value: _currentOption,
          items: options
              .map((option) => DropdownMenuItem(
                    child: Text(option),
                    value: option,
                  ))
              .toList(),
          onChanged: (value) => context.read(optionProvider).state = value,
        ),
      ),
    );
  }
}

final optionProvider = StateProvider<String>((ref) => options.first);

final options = List.generate(5, (index) => 'Option $index').toList();

Other State Management Systems

You have also other State Management packages available, as described here: https://flutter.dev/docs/development/data-and-backend/state-mgmt/options

Upvotes: 2

Nitesh
Nitesh

Reputation: 508

You can do it by creating a new class that will store the value for you.

Something like this:

      class Value {
        static String value;
        static void setString(String newValue) {
          value = newValue;
        }

        static String getString() {
          return value;
        }
      }

So, when your dropdown is clicked you can call the

Value.setString(value)

to store the value.

And on the 5th screen you can call the

Value.getString()

to get the stored value and use it.

Note: There are a lot of different ways to do it. But this is the simplest, according to me.

Upvotes: 1

Related Questions