Flutter

[Flutter] "The instance member 'example' can't be accessed in a initializer" Error

Hayden_ 2023. 3. 24. 01:50

The instance member 'id' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression
dartimplicit_this_reference_in_initializer

 

Flutter를 공부하던 중에 이와 같은 에러를 만나게 되었다.

이와 같은 에러가 난 코드를 일단 봐보자.

class DetailScreen extends StatelessWidget {
  final String title, thumb, id;

  DetailScreen({
    super.key,
    required this.title,
    required this.thumb,
    required this.id,
  });

  Future<List<WebtoonEpisodeModel>> webtoonEpisode = // ERROR
      ApiService.getLatestEpisodesById(id);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 2,
        foregroundColor: Colors.green,
        backgroundColor: Colors.white,
        title: Text(
          title,
          style: const TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      body: SomethingWidget...
          ),
        ],
      ),
    );
  }
}

Future 타입의 webtoonEpisode를 구하기 위해서 ApiService 객체를 이용하려고 하는데 메서드 getLatesEpisodesById에 id를 넘겨주려고 하는데 제목과 같은 에러가 나타났다.

 

일단 당연히 Future을 사용하니까 StatelessWidget에서는 당연히 에러가 나는 것이 아니냐고 생각할 수 있는데 이 에러는 Future때문에 나는 것이 아닌 id가 DetailScreen 객체의 인자값에 의해 결정되기 때문이다. 

 

Future을 쓰면서 Stateless Widget으로 남겨둔 이유는 FutureBuilder Widget을 사용하기 위해서이다. 하지만 id를 넘겨줄 수 없기 때문에 어쩔 수 없이 Stateful Widget으로 바꿔줘야지 이 에러가 사라질 것이다.

 

해결법

StatelessWidget 에서 StatefulWidget으로 바꿔준다!

 

당연한 건데 어떻게든 StatelessWidget을 써보려다가 이 에러를 만난 것 같다.