You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中初始化器无法访问实例成员_endeks的问题求助

Fixing "Can't access 'this' in a field initializer" Error in Flutter

Hey there! I see you're stuck with that frustrating error when trying to pass _endeks to your HomePage widget in the _pages list. Let's break down why this happens and fix it right away.

Why the Error Pops Up

In Dart, you can't access instance members (like _endeks) when initializing other instance fields directly in the class body. Here's the thing: when the class is being constructed, the object isn't fully set up yet. So this (and any variables tied to it, like _endeks) aren't available to use in field initializers. When you hardcode the list content, it works because you're using constant values that don't depend on the instance's state.

Solution 1: Initialize _pages in initState()

The most straightforward way in a Flutter State class is to use the initState() method. This method runs right after the state object is created, so all your instance variables are ready to use by then. Here's your modified code:

import 'package:flutter/material.dart';
import 'ana_sayfa.dart';
import 'alim_satim.dart';
import 'package:trade_online/e_takvim.dart';
import 'haberler.dart';
import 'piyasalar.dart';

class _BottomNavigationBar_bymeState extends State<BottomNavigationBar_byme> {
  IconThemeData ikonrengi = IconThemeData(
    color: Color.fromRGBO(180, 177, 168, 1),
  );
  List<String> dizi = <String>["Son", "%Fark", "Fark", "Düşük"];
  List<String> _endeks=["XAG/TR","XAG/USD","USD/TR","XAU/TR","EURO/TR"];
  int _selectedIndex = 0;
  // Declare _pages as late since we'll initialize it later
  late List<Widget> _pages;

  @override
  void initState() {
    super.initState();
    // Now we can safely access _endeks here
    _pages = [
      HomePage(true, _endeks),
      PiyasalarSayfasi(),
      Haberler(),
      E_Takvim(),
      Alim_Satim_Sign()
    ];
  }
}

Solution 2: Use late with a Lazy Initializer

If you prefer a more concise approach, you can use the late keyword with a lazy initializer. This tells Dart to wait until the variable is first accessed before running the initializer—by which time _endeks is fully available:

// Replace the original _pages declaration with this:
late List<Widget> _pages = [
  HomePage(true, _endeks),
  PiyasalarSayfasi(),
  Haberler(),
  E_Takvim(),
  Alim_Satim_Sign()
];

Both solutions will fix the error, but using initState() is generally preferred in Flutter State classes. It aligns with the widget lifecycle and makes your initialization logic more explicit, especially if you need to add extra setup steps later.

内容的提问来源于stack exchange,提问作者Yavuz Keskin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:17:44