如何在另一个类中使用创建的列表?

问题描述

当我创建一个列表时,我只能在我创建列表的班级中使用它。但是在另一个类中,当我想使用列表时,我收到一个错误“未定义名称”。我如何才能访问列表?

例如,在我的代码中,我创建了一个带有字符串的列表“计划”。

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

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

现在我想从 Appbar 中另一个 Widget 的列表计划中输出一个字符串作为标题,以便用户知道他在哪里。

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

我如何才能访问列表计划?

解决方法

一种选择是为您的 InheritedWidget 类创建和使用 State 样式的访问器,然后您可以从任何后代 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]}'),);
  }
}

一开始这可能会让人难以理解,但随着您对 Flutter's declarative framework 越来越熟悉,这会更有意义。

要使上面的示例工作,您需要有一个 MaterialApp 祖先小部件,并且您的 State 类(您保存 plans 状态对象的位置)需要是它的父母。我会在 similar question here 上解释原因。

您的另一个选择是使用 State Management package of which there are lots,它可以帮助您简化对状态对象的访问。