環境
- Flutter 3.0.1
- Dart 2.17.1
問題
Flutterを使っている時にsetStateで変数の中身を更新したいと思っていたのですが、なぜか「setState is not defined」とエラーが出力されてしまいコンパイルが通りませんでした。
出力されたメッセージはこちら↓
The function 'setState' isn't defined.
Try importing the library that defines 'setState', correcting the name to the name of an existing function, or defining a function named 'setState'.
![](https://atsu-developer.net/wp-content/uploads/2022/06/スクリーンショット-2022-06-08-15.28.07-1024x346.png)
解決方法
私の場合だと、setStateを使っているWidgetの定義をStatefulClassの外出ししていたためでした。
以下はその例となるソースです。(あくまでもイメージを深めてもらうために記述したので、多分これ自体は動きませんm(_ _)m)
class MenuDashboardPage extends StatefulWidget {
const MenuDashboardPage({Key? key}) : super(key: key);
@override
State<MenuDashboardPage> createState() => _MenuDashboardPageState();
}
class _MenuDashboardPageState extends State<MenuDashboardPage> {
bool isCollapsed = true;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[600],
body: Stack(
children: <Widget>[
dashboard(context),
],
),
);
}
}
Widget dashboard(context) {
return (
InkWell(
onTap: () {
setState(() {
isCollapsed = !isCollapsed;
});
},
child: Icon(
Icons.menu,
color: Colors.white,
),
),
)
}
上記ソースは、onTapによりisCollapsedの値を変更することを狙ってsetStateメソッドを使用しています。
前提としてsetStateはstatefulWidgetクラスにて宣言できるのであり、それ自体が定義されていないことで、今回のエラーが出力されているのです。
ですので、statefulWidgetクラスにdashboardメソッドを追加してあげる必要があります。
以下が解決方法を適用したソースです。(こちらもあくまでもイメージを浮かべて欲しいが故のソースですm(_ _)m)
class MenuDashboardPage extends StatefulWidget {
const MenuDashboardPage({Key? key}) : super(key: key);
@override
State<MenuDashboardPage> createState() => _MenuDashboardPageState();
}
class _MenuDashboardPageState extends State<MenuDashboardPage> {
bool isCollapsed = true;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[600],
body: Stack(
children: <Widget>[
dashboard(context),
],
),
);
}
Widget dashboard(context) {
return (
InkWell(
onTap: () {
setState(() {
isCollapsed = !isCollapsed;
});
},
child: Icon(
Icons.menu,
color: Colors.white,
),
),
)
}
}
上記のように修正することでsetStateメソッドを使用してisCollapsedフィールドを変更することがでいると思います。
おわり
コメント