Akella Niranjan
Akella Niranjan

Reputation: 95

Flutter: How to change the state of a variable in another dart file?

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.

Upvotes: 2

Views: 3288

Answers (2)

Balaji Venkatraman
Balaji Venkatraman

Reputation: 1337

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();
  }
}

Upvotes: 3

Fer Buero Trebino
Fer Buero Trebino

Reputation: 113

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),
      ), 
    );
  }
}

Upvotes: -1

Related Questions