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),
),
);
}
}
4
Answers
I solved it even tough I haven’t fully understood why this causes the problem.
The trailing property of your list tiles displays not the current index of the tile but rather the count of the amount of tiles. This will show the same string for every tile but should not make a problem adding more tiles. Nevertheless, change
Tile $_tileCount
toTile $index
to fix it.You are accessing
_tileCount
via_MyTileState()
, which is the Generic Object, not the current instance.You could use
this._tileCount
or just outright_tileCount
.You should use _tileCount instead of _MyTileState()._tileCount because u are creating new instace by calling constructor of class so it reverts to default.
if you want to explicitly point for this class u should use this._tileCount it refers to current class.
Every Think fine but the way you accessed the _tileCount is not valid
To access the _tileCount variable within the same class, you can directly refer to it by its name without mentioning the class, as they are both in the same scope.
so I just replaced
to
or
Here is the final Code :