Reputation: 1954
how do I change the 'state' in a StatefulWidget class but from an external function?
Examples are as follows:
in lib/main.dart
import 'package:flutter/material.dart';
import 'increment-count.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@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.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
I want to move the _incrementCounter function to another file. for example in 'lib/increment-count.dart'
.
in /lib/increment-count.dart
import 'package:flutter/material.dart';
void _incrementCounter() {
setState(() {
_counter++;
});
}
but the setState
instead displays an error "The function setState
isn't defined".
can anyone help?
Upvotes: 3
Views: 1310
Reputation: 4392
Moving function in another file in this example has no point but here is the solution. Obviously it is a great idea for a bigger function which you want to reuse somewhere else
in your new file increment-count.dart add this
int incrementCounter(int counter) {
return counter + 1;
}
and then call it in your main class
onPressed: () => setState(() {
_counter = incrementCounter(_counter);
})
However answer to your question, how to setState from external function, is not possible.
Upvotes: 4
Reputation: 2714
your'e getting this error "The function setState isn't defined"
because the second file is no stateful widget which can take up a setState function. and if you then want to increment the counter you have no access, as it is marked as private and the logic part is in a different file.
Than BloC pattern or providers is what you need. Since I'm also still beginner, I can recommend you using providers, as it is quite easy to learn and it does exactly what you want.
https://pub.dev/packages/provider
with this you can like globally define this function and use it in different files.
This can look like this for example (toggleCounter()
would be the global function then):
final counterIncrement = Provider.of<Data>(context).toggleCounter();
Upvotes: 2