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
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).Using StatefulWidget is a good starting point for beginners, and there are various libraries and methods available to explore.
StatefulWidgets workflow is:
createState() method is called, which returns an instance of the
corresponding State object.
variables, setting up listeners, and other one-time setup.
method, which triggers a rebuild of the widget.
hierarchy with the updated state.
the dispose() method to perform cleanup.
now to update text:
you must declare String or var in
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