1

When i create a list, i can only use it in the class where i created the list. But in another class i get an error 'undefined name' when i want to use the list. How can i get access to the list?

For example in my code i created a list 'plans' with strings.

class _PlanOverviewState extends State<PlanOverview> {
  List<String> plans = ['Plan A', 'Plan B'];

  void addPlan(String neuerPlan) {
    setState(() {
      plans.add(neuerPlan);
    });
    Navigator.of(context).pop();
  }

Now I want to output a single string from the list plans in another Widget in the Appbar as title, so the User know where he is.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(plans[i]))

How can i get access to the list plans?

Dalon
  • 566
  • 8
  • 26

1 Answers1

0

One option is to create & use an InheritedWidget-style accessor for your State class and then you can access it from any descendant context.

import 'package:flutter/material.dart';

class InheritedWidgetPage extends StatefulWidget {
  @override
  _InheritedWidgetPageState createState() => _InheritedWidgetPageState();

  static _InheritedWidgetPageState of(BuildContext context) =>
      context.findAncestorStateOfType<_InheritedWidgetPageState>();
}

class _InheritedWidgetPageState extends State<InheritedWidgetPage> {
  List<String> plans = ['Plan A', 'Plan B'];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    _InheritedWidgetPageState _state = InheritedWidgetPage.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(_state.plans[0]),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Goto ${_state.plans[1]}'),
          onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => PlanPage(1))),
        ),
      ),
    );
  }
}

class PlanPage extends StatelessWidget {
  final int index;

  PlanPage(this.index);

  @override
  Widget build(BuildContext context) {
    _InheritedWidgetPageState _state = InheritedWidgetPage.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(_state.plans[index]),
      ),
      body: Center(
        child: Text('You are here: ${_state.plans[index]}'),
      ),
    );
  }
}

This can be pretty confusing to understand at first, but will make more sense as you get more familiar with Flutter's declarative framework.

For the above example to work, you need to have a MaterialApp ancestor widget, and your State class (where you're holding your plans state object) needs to be its parent. I explain why on a similar question here.

Your other option is to use a State Management package of which there are lots, which can help you simplify access to state objects.

Baker
  • 24,730
  • 11
  • 100
  • 106