skip to Main Content

I have written the following code below in Flutter.

import 'dart:async';
import 'package:flutter/material.dart';

int _counter = 0;

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

void _updateCounter() {
  Timer.periodic(Duration(seconds: 1), (timer) {
      _counter++;
      print('$_counter');
  });
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
//This text widget needs to be updated automatically, but how?
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

I have a timer, and every second the value of a variable can change. For example, it can be the status of the connection to a Bluetooth device.

How to update text widget in class _MyHomePageState with content _counter?
The funktion _updateCounter must be called from main.

2

Answers


  1. You can use ValueNotifier for this single value, but on mid>= level project level, you may choose state-mangement solution like riverpod/bloc(make things easier).

    import 'dart:async';
    import 'package:flutter/material.dart';
    
    ValueNotifier<int> _counter = ValueNotifier(0);
    
    void main() {
      runApp(const MyApp());
      _updateCounter();
    }
    
    void _updateCounter() {
      Timer.periodic(Duration(seconds: 1), (timer) {
        _counter.value++;
        print('$_counter');
      });
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      const MyHomePage({super.key, required this.title});
      final String title;
    
      void _incrementCounter() {
        _counter.value++;
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ValueListenableBuilder<int>(
                  valueListenable: _counter,
                  builder: (context, value, child) => Text(
                    '$value',
                  ),
                  //
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    
    
    Login or Signup to reply.
  2. Using StatefulWidget is a good starting point for beginners, and there are various libraries and methods available to explore.
    StatefulWidgets workflow is:

    1. The StatefulWidget is created by calling its constructor. The
      createState() method is called, which returns an instance of the
      corresponding State object.
    2. initState() method is called, which is used for initializing
      variables, setting up listeners, and other one-time setup.
    3. build() method is called, which builds the widget hierarchy.
    4. When the widget is updated, the framework calls the setState()
      method, which triggers a rebuild of the widget.
    5. The framework calls the build() method again to rebuild the widget
      hierarchy with the updated state.
    6. If the widget is removed from the widget tree, the framework calls
      the dispose() method to perform cleanup.

    now to update text:
    you must declare String or var in

    class _MyHomePageState extends State<MyHomePage> {
    var a='test';
    }
    

    then write function like _incrementCounter and in int change your text and call setState() and den call the function (like _incrementCounter) in the app in this example button do it for you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search