Joao Marcos
Joao Marcos

Reputation: 13

instance member cant be accessed in an initializer

well, I'm trying to create a really simple app with a bottom navigation bar and for so I created a list that lists what to be displayed in each page, the problem is that I wana have a floating button that increments a counter everytime I press it but when I do the thing to display on screen the counter inside the list, it gives me the error mesage: The instance member 'counter' can't be accessed in an initializer. Just to clarify, the problem is right on the beggining of the code on the list, where I put the ${counter} My code:

import 'package:flutter_speed_dial/flutter_speed_dial.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => new _State();
}
class _State extends State<MyApp> {
  int counter = 0;

  void resetCounter() {
    setState(() {
      counter = 0;
    });
  }

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  List<Widget> _pages = <Widget>[
    Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(),
        Container(
          padding: EdgeInsets.all(15),
          margin: EdgeInsets.all(10),
          color: Colors.grey[300],
          child: Text(
            'lets see how many times you click it',
            style: TextStyle(
              fontSize: 15,
              fontFamily: 'IndieFlower',
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Text(
          'button clicks - ${counter}',
          style: TextStyle(
            fontFamily: 'IndieFlower',
            fontWeight: FontWeight.bold,
            color: Colors.blue[600],
            fontSize: 20,
            letterSpacing: 3,
          ),
        ),
      ],
    ),
    Icon(
      Icons.camera,
      size: 150,
    ),
  ];
  int _selectedIndex = 0;
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('button test'),
          centerTitle: true,
          backgroundColor: Colors.blue[400],
        ),
        body: Center(
          child: _pages.elementAt(_selectedIndex),
        ),
        floatingActionButton: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FloatingActionButton(
                child: Icon(
                    Icons.restart_alt
                ),
                onPressed: () {
                  resetCounter();
                },
                heroTag: null,
              ),
              SizedBox(
                height: 10,
              ),
              FloatingActionButton(
                child: Icon(
                    Icons.plus_one
                ),
                backgroundColor: counter == 10 ? Colors.grey : Colors.blue,
                onPressed: () =>
                counter < 10 ? incrementCounter() : ScaffoldMessenger.of(context)
                    .showSnackBar(SnackBar(content: Text(
                  'limit reached',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ))),
                heroTag: null,
              )
            ]
        ),
        bottomNavigationBar: BottomNavigationBar(
        items: const<BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.add_photo_alternate_outlined),
            label: 'page 2',
          ),
        ],
          currentIndex: _selectedIndex,
          onTap: _onItemTapped,
    ),
    );
  }
}

Upvotes: 1

Views: 1264

Answers (1)

WSBT
WSBT

Reputation: 36323

Two solutions:

The quickest fix is to add late keyword, like so:

late List<Widget> _pages = <Widget>[
  ...
];

Another solution is to move your List<Widget> _pages = [...]; variable declaration inside the build method.

Both solutions achieves the same goal: delay accessing the variable ($counter) until when it's needed (i.e. when building the widget).

By the way, new keyword is no longer needed in Dart. You should remove all of them. For example, createState() => new _State() should just be createState() => _State().

Upvotes: 4

Related Questions