将项目添加到列表中不会呈现新项目(AnimatedList)

时间:2021-06-19 17:48:34

标签: flutter flutter-animation

我想我快疯了或者颤振有什么问题。

当我将项目添加到列表中时,我可以看到列表的长度改变了所有呈现的内容,但列表不会呈现新项目。

如果我使用简单的 ListView.builder 一切正常,所以我怀疑我在 AnimatedList 小部件上做错了。

import 'package:chat/providers/message.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:timeago/timeago.dart' as timeago;

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => Messages()),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tornike Razmadze',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Tornike Razmadze'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();

  @override
  Widget build(BuildContext context) {
    return Consumer<Messages>(builder: (context, msgs, child) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: SafeArea(
          child: Column(
            children: [
              messages(msgs),
              chatInput(msgs),
            ],
          ),
        ),
      );
    });
  }

  Widget messages(Messages msgs) {
    print('messages length: $msgs');
    return Expanded(
      child: AnimatedList(
        key: listKey,
        reverse: true,
        initialItemCount: msgs.messages.length,
        //itemCount: msgs.length,
        itemBuilder: (context, index, animation) {
          Message message = msgs.messages[index];
          print('msg: ${message.body} index: $index');
          return SizeTransition(
            axis: Axis.vertical,
            sizeFactor: animation,
            child: msgItem(message),
          );
        },
      ),
    );
  }

  Widget msgItem(Message message) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(10.0),
      child: Column(
        crossAxisAlignment:
            message.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(bottom: 4),
            child: Text(
              (message.isMe)
                  ? 'Tornike ${timeago.format(message.createdAt)}'
                  : '${message.from} ${timeago.format(message.createdAt)}',
              style: TextStyle(
                fontSize: 12.0,
                color: Colors.black54,
              ),
            ),
          ),
          Material(
            borderRadius: message.isMe
                ? BorderRadius.only(
                    topLeft: Radius.circular(30.0),
                    bottomLeft: Radius.circular(30.0),
                    bottomRight: Radius.circular(30.0))
                : BorderRadius.only(
                    bottomLeft: Radius.circular(30.0),
                    bottomRight: Radius.circular(30.0),
                    topRight: Radius.circular(30.0),
                  ),
            elevation: 5.0,
            color: message.isMe ? Colors.blue : Colors.white,
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
              child: Text(
                message.body,
                style: TextStyle(
                  color: message.isMe ? Colors.white : Colors.black54,
                  fontSize: 15.0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget chatInput(Messages msgs) {
    var _controller = TextEditingController();
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(5.0),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey,
            offset: Offset(0.0, 1.0), //(x,y)
            blurRadius: 6.0,
          ),
        ],
      ),
      child: TextField(
        controller: _controller,
        // focusNode: myFocusNode,
        onSubmitted: (val) async {
          msgs.send(val);
          _controller.clear();
        },
        autofocus: true,
        decoration: InputDecoration(
          prefixText: '   ',
          suffixIcon: IconButton(
            onPressed: () {
              msgs.send(_controller.text);
              _controller.clear();
            },
            icon: Icon(
              Icons.send,
              color: Colors.lightBlue,
              size: 24.0,
              semanticLabel: 'Text to announce in accessibility modes',
            ),
          ),
        ),
      ),
    );
  }
}

这是提供者,这很简单,但行不通

import 'package:flutter/material.dart';

class Message {
  String from;
  String body;
  DateTime createdAt;
  bool isMe;
  Message(this.from, this.body, this.createdAt, {this.isMe = false});
}

class Messages extends ChangeNotifier {
  List<Message> _msgs = [];

  Messages() {
    _msgs.add(
        Message("Tornike", "How are you doing", DateTime.now(), isMe: true));
    _msgs.add(Message("Tornike", "Hi", DateTime.now(), isMe: true));
    notifyListeners();
  }

  send(String body) {
    _msgs.add(Message("Guest", body, DateTime.now(), isMe: false));
    print('_msgs length: ${_msgs.length}');
    notifyListeners();
  }

  List<Message> get messages {
    print('_msgs (getter) length: ${_msgs.length}');
    return _msgs;
  }
}

任何建议将不胜感激。

0 个答案:

没有答案