向地图中的列表添加值的正确方法是什么?

时间:2019-06-20 12:52:50

标签: flutter save maps

我正在创建Flutter应用程序,我希望用户能够在其中将事件(字符串)添加到Map (Map<DateTime, List<String>>)中的列表中。然后在屏幕上显示它们(稍后在listView上显示)。

这是“事件”和“日期选择器”所在的类:

class EventBrain {
  final Map<DateTime, List<String>> events = {};

  Future<Null> addEvent(BuildContext context, String title) async {
    final dtPick = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2019),
      lastDate: DateTime(2021),
    );
    if (events.containsKey(dtPick) == true) {
      events[dtPick].add(title);
      print(events[dtPick]);
    } else if (dtPick != null) {
      events.putIfAbsent(dtPick, () => <String>[]).add(title);
      print(events[dtPick]);
    }
  }
}

这是希望在其上打印的屏幕:

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ABC'),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
        setState(() {
          EventBrain().addEvent(context, 'NewEvent');
        });
      }),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[Text(EventBrain().events.toString())],
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:2)

每次想在每种情况下都使用同一实例时,每次添加事件或尝试从EventBrain中读取事件时,您都在创建一个新实例。

class _MyHomePageState extends State<MyHomePage> {
  final _eventBrain = EventBrain();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ABC'),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () async {
        final dtPick = await showDatePicker(
          context: context,
          initialDate: DateTime.now(),
          firstDate: DateTime(2019),
          lastDate: DateTime(2021),
        );
        setState(() {
          _eventBrain.addEvent('NewEvent', dtPick);
        });
      }),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[Text(_eventBrain.events.toString())],
        ),
      ),
    );
  }
}

此外,我认为将上下文限制在您的Widget中是一种好习惯,这使得测试和代码重用变得更加容易,因此您的EventBrain类如下所示:

class EventBrain {
  final Map<DateTime, List<String>> events = {};

  Future<Null> addEvent(String title, DateTime dtPick) async {
    if (events.containsKey(dtPick) == true) {
      events[dtPick].add(title);
      print(events[dtPick]);
    } else if (dtPick != null) {
      events.putIfAbsent(dtPick, () => <String>[]).add(title);
      print(events[dtPick]);
    }
  }
}