Flutter中初始化器无法访问实例成员_endeks的问题求助
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

