I'm currently learning flutter and I'm having trouble managing states. I used this flutter guide as a reference: https://docs.flutter.dev/ui/interactive#managing-state.
I'm getting an exception thrown: "Lookup failed: addTiles in @methods in _MyTileState in package:app_recipes/main.dart"
This is my code:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
const MyHome({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('My App'),
),
body: const MyTile(),
);
}
}
class MyTile extends StatefulWidget {
const MyTile({super.key});
@override
State<MyTile> createState() => _MyTileState();
}
class _MyTileState extends State<MyTile> {
int _tileCount = 5;
void _addTiles()
{
setState(() {
_tileCount += 1;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: _MyTileState()._tileCount,
itemBuilder: (BuildContext context, index)
{
return ListTile(
leading: const Icon(Icons.list),
trailing: Text(
'Tile $_tileCount'
),
);
}
),
floatingActionButton: FloatingActionButton(
onPressed: _addTiles,
child: const Icon(Icons.add),
),
);
}
}
You are accessing _tileCount
via _MyTileState()
, which is the Generic Object, not the current instance.
You could use this._tileCount
or just outright _tileCount
.