2

I am currently working on an app; I want to change the value of a String which is declared in another dart file and then pass that changed state to the stateful widget.

I.E;

  1. I create a file called as "Body.dart" file where I have declared a String called as 'scale' who's value initially is "Empty".

  2. Later when a button in another dart file "scale_button" is pressed, I want to assign the string scale = "Hello" in my Body.dart file. So that the stateful widget also displays the same on the screen.

2
  • 1
    Share samples of your code. Commented Jan 21, 2021 at 15:41
  • 1
    This is global state management, if you didn't get to research anything then I believe that this flutter doc should help you.
    – Chance
    Commented Jan 21, 2021 at 15:47

2 Answers 2

3

You can use provider(or any other state management) 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> {
  StringProvider _stringProvider;

  @override
  void initState() {
    super.initState();
    _stringProvider = Provider.of<StringProvider>(context, listen: false);
  }

  void updateString() {
    _stringProvider.setString('hai');
  }

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

class StringProvider extends ChangeNotifier { // create a common file for data
  String _str = 'hello';

  String get str => _str;

  void setString(String st) {
    _str = st;
    notifyListeners();
  }
}
6
  • Balaji, Thank you for providing the code for integer. But can you please tell me how to do the same with string. I want to be able to change the string value when a button is pressed. Commented Jan 22, 2021 at 11:13
  • @AkellaNiranjan I have updated the code for the string. Let me know if that works Commented Jan 22, 2021 at 13:22
  • 1
    Hello Balaji, I want to do the "_stringProvider.setString('hai')" in a different dart file. The code which you have given above is only working if I try to set the new string in the same dart file. But instead I would like to set the new string in a different dart file. Commented Jan 24, 2021 at 11:23
  • @AkellaNiranjan you have to use this kind of approach only and you can refer the value wherever wanted and also you change the value wherever you wanted.You can follow the same approach Commented Jan 25, 2021 at 7:55
  • Venkataraman, Could you also help me with one more thing, Do you know how to generate sound in flutter app. Like I am currently working on a musical app like "Tanpura". Could you please tell me how can I generate my own sound of various frequencies in flutter. Commented Jan 25, 2021 at 15:05
-1

When you create a new Flutter project the sample code of the counter shows you how to do this. Check out the comments in the next code:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // here is passing a String to MyHomePage.
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  // And here you can see how to make the widget wait for a variable 
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Full code of Sample Counter App

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  _MyHomePageState 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>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), 
    );
  }
}
6
  • This will not work please provider full code Commented Jan 21, 2021 at 19:47
  • Belaji, you just need to open Android Studio o VS code and create a new flutter project, when you create a new project, it cames with a counter app example, the code I put is from there, Commented Jan 22, 2021 at 4:17
  • @FerBueroTrebino Your solution only works if I am changing the value in the same dart file. But what I need is that I want to change the value of a string in a different dart file and it should reflect in the present dart file. Commented Jan 22, 2021 at 11:12
  • @FerBueroTrebino I understood that it comes as a flutter sample when creating a flutter app.The Thing is if you are answering here it should be clear and helpful Commented Jan 22, 2021 at 13:21
  • @AkellaNiranjan I was trying to help you to achieve it with a simple explanation, but the correct answer was given by JustCase yesterday. "This is global state management, if you didn't get to research anything then I believe that this flutter doc should help you." Commented Jan 22, 2021 at 16:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.